Skip to content

Custom Generic Methods & Functions

Roman Jámbor edited this page Feb 27, 2022 · 6 revisions

Custom Generic Methods & Functions

It is possible to declare any method and function and just use the generic T in getType<T>() call.

function printTypeFullName<TType>() {
    console.log(getType<TType>().fullName);
}

class Animal {}

printTypeFullName<Animal>();

But there are some limitations on abstract classes and interfaces.

import { getType } from 'tst-reflect';

interface IFace {
    doSomethingWithType<TType>();
}

class Clss implements IFace {
    doSomethingWithType<TType>() {
        const type = getType<TType>();
        console.log(getType<TType>().fullName);
    }
}

const foo: IFace = new Clss(); // Clss as Iface

class Animal {}

foo.doSomethingWithType<Animal>(); // Will not work!

Example will not work, because transformer is looking for usage of getType<>() inside called functions and methods but doSomethingWithType is called over the interface which has no implementation so there is no usage of getType<>(). For this cases there is JSDoc tag @reflect which force transformer to pass information about all generic types.

interface IFace {
    /**
     * @reflect
     */
    doSomethingWithType<TType>();
}

Decorator would be nicer, but it is not generated on interfaces nor abstract things by the TypeScript, because it does not exist on runtime.

Clone this wiki locally