Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript keyof a class

I want to pass a class to a function and infer the keys of the class but it doesn’t work:

class Foo {
  bar: string;
}

function foo<C>(comp: C, key: keyof C) {

}

foo(Foo, '') // expecting to get bar here, but I'm getting the prototype key

When I use it as a type, it works:

type Keys = keyof Foo;

What’s the issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

FIrst of all you need to provide initializer for bar property.
Second of all, you are passing class constructor as an argument and expect second to be bar. It can be bar only if you provide an instance of Foo class. If you want to get bar you need to use InstanceType utility type, in other words, get keys from class instance instead of class constructor:

class Foo {
  bar: string = ''
}
type AnyClass = new (...args: any[]) => any

function foo<C extends AnyClass>(comp: C, key: keyof InstanceType<C>) {

}

foo(Foo, 'bar') // ok
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading