I am using the following type in my TypScript:
interface ExerciseData {
id : number;
name : string;
vocabulary : {
from : string;
to : string;
}[];
}
Now I'd like to create a variable that is of the same type as the attribute vocabulary
, trying the following:
var vocabs : ExerciseData.vocabulary[];
But that is not working. Is it possible to reference to a subtype somehow? Or would I have to do something like this?
interface ExerciseData {
id : number;
name : string;
vocabulary : Vocabulary[];
}
interface Vocabulary {
from : string;
to : string;
}
var vocabs : Vocabulary[];
Thanks a lot for hints.
Since TypeScript 2.1 you can do the following using lookup types:
type vocabulary = ExerciseData['vocabulary'][]; // Array<{from: string, to: string}>
These lookup types can also be chained. For example, to get the type of the from
field you can do the following:
type from = ExerciseData['vocabulary'][number]['from']; // string
For complex scenario's it's also possible to base the lookup type on another type as follows:
type fieldKey = 'id' | 'name';
type fieldTypes = ExerciseData[fieldKey]; // number | string