Answer the question
In order to leave comments, you need to log in
How to create a typed interface?
There is a class whose property type cannot be known in advance. I.e
class SomeClass {
public data: any;
}
interface IData<any> {}
class SomeClass {
public data: IData<any>;
}
interface IData<any> {}
interface ISomeData {
value: number;
}
class SomeClass {
public data: IData<any>;
}
let data: IData<ISomeData> = new SomeClass().data;
Answer the question
In order to leave comments, you need to log in
1) Parametrize the class:
class SomeClass<T> {
public data: T;
}
let numData: number = new SomeClass<number>().data;
let strData: string = new SomeClass<string>().data;
class SomeClass {
data: any;
}
let numData: number = new SomeClass().data as number;
let strData: string = new SomeClass().data as string;
An interface is needed to describe a certain general contract that all implementations of this interface must support. In this case, IData does not implement any contracts and, as for me, does not make any sense. If you need to store data of any type in SomeClass , then let it remain any , which then, if necessary, can be cast into anything.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question