TypeScript: reference subtype of type definition (interface)

I use the following type in my TypScript:

interface ExerciseData { id : number; name : string; vocabulary : { from : string; to : string; }[]; } 

Now I would like to create a variable of the same type as the vocabulary attribute, by trying the following:

 var vocabs : ExerciseData.vocabulary[]; 

But that does not work. Is there any way to refer to a subtype? Or did I need to do something like this?

 interface ExerciseData { id : number; name : string; vocabulary : Vocabulary[]; } interface Vocabulary { from : string; to : string; } var vocabs : Vocabulary[]; 

Thanks so much for the tips.

+7
javascript typescript typing
source share
2 answers

Not quite what you want, but you can hack it with the typof keyword, but only if you have var, which is declared as your interface type, as shown below. Please note that I think what you did in your latest codeblood is much better :)

 interface ExerciseData { id : number; name : string; vocabulary : { from : string; to : string; }[]; } var x: ExerciseData; var vocabs : typeof x.vocabulary[]; 
+2
source share

Since TypeScript 2.1 you can use the following search types:

 let vocabs: ExerciseData['vocabulary'][]; 
+4
source share

All Articles