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]? }
keyof typeof will infer the type of a javascript object and return a type that is the union of its keys. Because it can infer the exact value of the keys it can return a union of their literal types instead of just returning "string".
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
Definition of TypeScript typeof. typeof in TypeScript has the same name like JavaScript but functions differently. typeof is used to differentiate between the different types in TypeScript. By the use of typeof we can differentiate between number, string, symbol, Boolean, etc.
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']
.
Yes, lookup types work just fine:
type BarType = FooType['bar'];
It expects in this case that FooType
is an object like:
type FooType = { bar: string; }
It sets BarType
to the same type as FooType['bar']
, so to a string
.
PS: FooType
can also be an interface or class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With