TypeScript: Reference subtype of type definition (interface)

只谈情不闲聊 提交于 2019-12-04 00:15:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!