C
C
copal2016-04-14 14:00:31
typescript
copal, 2016-04-14 14:00:31

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

So I want to do something like -
interface IData<any> {}

class SomeClass {
    public data: IData<any>;
}

And then add the type
interface IData<any> {}
interface ISomeData {
    value: number;
}
class SomeClass {
    public data: IData<any>;
}

let data: IData<ISomeData> = new SomeClass().data;

How to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bromzh, 2016-06-01
@copal

1) Parametrize the class:

class SomeClass<T> {
    public data: T;
}
let numData: number = new SomeClass<number>().data;
let strData: string = new SomeClass<string>().data;

2) Cast types:
class SomeClass {
  data: any;
}
let numData: number = new SomeClass().data as number;
let strData: string = new SomeClass().data as string;

But it is important to remember that these types will not be in runtime. In fact, if the data field contains a number, and you cast it to a string, then no conversion will really take place.
Also worth a look here: https://www.typescriptlang.org/docs/handbook/advan...

M
Maa-Kut, 2016-04-20
@Maa-Kut

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 question

Ask a Question

731 491 924 answers to any question