Home:ALL Converter>Class type as parameter in TypeScript

Class type as parameter in TypeScript

Ask Time:2019-08-16T21:26:23         Author:Patrik Valkovič

Json Formatter

I am a bit stuck with the type hinting in TypeScript when the parameter is class of specific type. I am trying to implement an event system and when I use the code from TypeScript playground, everything works fine for pure JavaScript. However, the standard compilation cause Errors of "TS2693: 'C1' only refers to a type, but is being used as a value here." How can I type-hint this method?

function method
<C1 extends BaseClass, C2 extends BaseClass>
(c1: typeof C1, c2: typeof C2, callback: (arg1: C1, arg2: C2) => void){
    // ...
}

Full example:

abstract class BaseClass {}

const dict = {}

function method
<C1 extends BaseClass, C2 extends BaseClass>
(c1: typeof C1, c2: typeof C2, callback: (arg1: C1, arg2: C2) => void){
    dict[c1] = dict[c1] || {};
    dict[c1][c2] = dict[c1][c2] || [];
    dict[c1][c2].push(callback);
}


class MyClass1 extends BaseClass{}
class MyClass2 extends BaseClass{}


method(MyClass1, MyClass2, (arg1: MyClass1, arg2: MyClass2) => {
    console.log("Callback");
});

const c1 = new MyClass1();
const c2 = new MyClass2();
dict[MyClass1][MyClass2][0](c1, c2);

Author:Patrik Valkovič,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57525497/class-type-as-parameter-in-typescript
yy