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?

>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

Leave a Reply