Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting type of a property of a typescript class using keyof operator

Tags:

typescript

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]? } 
like image 636
bmdelacruz Avatar asked Aug 26 '17 10:08

bmdelacruz


People also ask

What is Keyof typeof in TypeScript?

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".

How do you get the properties name of an object in TypeScript?

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] .

How do you check the datatype of a variable in TypeScript?

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.

What is typeof for a class 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.


2 Answers

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'].

like image 106
Oscar Avatar answered Nov 01 '22 20:11

Oscar


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.

like image 23
flori Avatar answered Nov 01 '22 21:11

flori