Issue
As stated in the documentation of Typescript about the keyof operator, one can get a property of an object instance using the function below.
function getProperty<T, K extends keyof T>(o: T, name: K) {
return o[name];
}
Of course, one can get the type of the property by replacing return o[name] into return typeof o[name]. Is there a way to retrieve the type of the property without passing any object instance?
function getPropertyType<T>(name: keyof T) {
// something like T[name]?
}
Solution
Is this what you're looking for?
type PropType<TObj, TProp extends keyof TObj> = TObj[TProp];
and get type of an object property by doing:
type MyPropType = PropType<ObjType, '<key>'>;
which is the same as the way of using Pick in typescript, and it can report compile error if there's any invalid key passed in.
Updates
As @astoilkov suggested, a simpler alternative is PropType['key'].
Answered By - Oscar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.