undefined
undefined

Reputation: 6864

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?

Upvotes: 1

Views: 710

Answers (2)

Dimava
Dimava

Reputation: 10879

You have

var Foo = class Foo { ... }
foo(/* new () => Foo */ Foo, /* 'prototype' */ ...)

because Foo is a class (i.e. a function) and not an instance of Foo class

Upvotes: 0

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

Upvotes: 6

Related Questions