0

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";
    }
}

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.