I want to pass obj to selectMap with typescript support.
And I want to make sure the keys pass to the function. I don't want to check the value type.
How I can achieve this with typescript? I have try to do keyof but typescript throw error.
interface User {
id: number;
firstName: string;
age: number;
}
function selectMap<T>(obj: keyof T) {}
selectMap<User>({
id: 'id',
firstName: 'first_name',
age: 'age'
})
CodePudding user response:
You can use the Record<K, V> utility type to mean "an object whose keys are of type K and whose values are of type V". You want obj to be a value of a type like Record<keyof T, any> instead of just keyof T:
function selectMap<T>(obj: Record<keyof T, any>) { }
selectMap<User>({
id: 'id',
firstName: 'first_name',
age: 'age'
}); // okay
