Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell `keyof MyClass.prototype` in TypeScript?

Tags:

typescript

In TypeScript I can define generic and force that in genericForObj passing only properties of a particular object.

class MyClass
{
  one(){};
  two(){};
}

function genericForObj<T, K extends keyof T>(obj: T, prop: K)
{

}

const obj = new MyClass;

genericForObj(obj, 'one'); // OK

genericForObj(MyClass, 'one');
// Error: Argument of type '"one"' is not
// assignable to parameter of type '"prototype"'.

How to tell keyof MyClass.prototype in generic function?

like image 256
ktretyak Avatar asked Oct 20 '25 02:10

ktretyak


2 Answers

Thanks to @gcnew, the following genericForClass does exactly what I wanted:

class MyClass
{
  one(c: boolean){};
  two(){};
}

function genericForClass
<T extends Function, K extends keyof T['prototype']>
(classHandler: T, method: K)
{

}

genericForClass(MyClass, 'one') // OK
genericForClass(MyClass, 'fake') // Error
like image 140
ktretyak Avatar answered Oct 22 '25 05:10

ktretyak


the code below returns all properties and methods of a class:

keyof typeof MyClass['prototype']
like image 42
HANNAN Std Avatar answered Oct 22 '25 04:10

HANNAN Std



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!