Michał Wojas
Michał Wojas

Reputation: 519

Define class which returns passed argument with its own types

I need to create new class with 2 arguments. One of them can be different type each time I create new class.

class Some{
    constructor(type:string, data?){
        this.type = type;
        this.data = data;
    }
}

And in my IDE I want to see what is typeof data for each Some instance, because it could be number, string or object with custom keys.

I was trying to do something like this: type IType<T> = T but still, I do not know then how to get T inside my class and when I return IType data it just not works.

And sorry, maybe it is not possible or just trivial but I am not good at TypeScript yet.

Upvotes: 0

Views: 26

Answers (1)

Tom Cumming
Tom Cumming

Reputation: 1168

class Some<T>{
    constructor(
        private type: string,
        public data: T
    ) {
    }

    foo() {
        console.log(`my type is ${this.type} and my data is ${this.data}`)
    }
}

const bar = new Some('hello', 123);
bar.data; // Hover over me to see type in your IDE
bar.foo();

Upvotes: 1

Related Questions