Home > Software design >  Typescript keyof a class
Typescript keyof a class

Time:11-23

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related