I want to write a generic function that takes as argument the name of the property of the generic type. I need to make TypeScript assert that the value of the property is of a specific type. Consider the following simplified code:
interface MyObject {
myProp: number;
mySecondProp: string;
myOtherProp: string;
myFlagProp: boolean;
}
const doStuff<T> = (obj: T, propName: SomeType) => { /***/ }
I can extract all the properties of a specific type (e.g. string
) but then the compiler would not know exactly the type of the property:
type StringProps<T> = {
[K in keyof T]: T[K] extends string ? K : never }[keyof T]
}
const doStuff<T> = (obj: T, propName: StringProps<T>) => {
obj[propName].indexOf("a"); // Property 'indexOf' does not exist on type 'T[{ [K in keyof T]: T[K] extends string ? K : never; }[keyof T]]'
}
What can I do to make the compiler understand that it should only accept string property names and that the value is always of type string
?