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

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.


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

Tags:

Typescript