问题
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.
回答1:
Not exactly what you want but you can hack around this with the typof keyword but only if you have a var that is declared as your interface type like below. Note that I think what you did in your last codeblock is a lot better :)
interface ExerciseData {
id : number;
name : string;
vocabulary : {
from : string;
to : string;
}[];
}
var x: ExerciseData;
var vocabs : typeof x.vocabulary[];
回答2:
Since TypeScript 2.1 you can do the following using lookup types:
let vocabs: ExerciseData['vocabulary'][];
来源:https://stackoverflow.com/questions/27875483/typescript-reference-subtype-of-type-definition-interface