Question

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";
    }
}
Was it helpful?

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

OTHER TIPS

Thanx basarat. You point me to right direction. My code now looks better.

export class LocalStorage<T> implements ILocalStorage<T> {
    private instance: any;
    constructor(instance: any) {
        this.instance = new instance(null);
    }

    getKey(): string {
        if (this.instance instanceof g.Group)
            return "Groups";
        else 
            return "Invalid";
    }
}

//using
var groupLocalStorage = new ls.LocalStorage<g.Group>(g.Group);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top