Search code examples
javascripttypescriptinstanceoftypeoftype-parameter

TypeScript using type parameter


How can I use type parameter T in next code block (typeOf, instanceOf,...). T is 'Group'. Is it possible because JavaScript does not have types. Thanx.

export class LocalStorage<T> implements ILocalStorage<T> {
    constructor() {}

    getKey(): string {
        if (T is 'Group')
            return "Groups";
    }
}

Solution

  • You cannot do it for TypeArguments in generics (as you have already realized). But you can do runtime checking if you use TypeScript classes:

    class Group{}
    
    
    function getKey(item:any): string { 
        if (item instanceof Group)
            return "Groups";
        else
            return 'invalid';
    }
    
    
    console.log(getKey(new Group()));
    

    There is no typescript magic in the above code. We are simply utilizing the javascript instanceof operator : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof