Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given a generic object (T) and a key of that object (K), can I constrain K to only those keys with a string value?

Very basic example of what I’d like to do:

function extractStringValue<T extends object, K extends keyof T>(obj: T, key: K): string {
    return obj[key]; // error: Type 'T[K]' is not assignable to type 'string'
}

// Desired usage

const myObj = { stringKey: "hi", boolKey: false }
const stringVal = extractStringValue(myObj, "stringKey"); // all OK
const stringVal2 = extractStringValue(myObj, "boolKey"); // should raise error

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should define T based on K. Since you want T[K] to be a string you have to change T to extend a Record<K, string>, since we don’t need anything else this definition is enough:

function extractStringValue<T extends Record<K, string>, K extends keyof T & string>(
  obj: T,
  key: K,
): string {
  return obj[key]; 
}

Usage:

const myObj = { stringKey: 'hi', boolKey: false };
const stringVal = extractStringValue(myObj, 'stringKey'); // all OK
const stringVal2 = extractStringValue(myObj, 'boolKey'); // expected error
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading