我在我的 TypScript 中使用以下类型:
interface ExerciseData {
id : number;
name : string;
vocabulary : {
from : string;
to : string;
}[];
}
现在我想创建一个与属性 vocabulary
类型相同的变量,尝试以下操作:
var vocabs : ExerciseData.vocabulary[];
但这不起作用。是否有可能以某种方式引用子类型?或者我必须做这样的事情吗?
interface ExerciseData {
id : number;
name : string;
vocabulary : Vocabulary[];
}
interface Vocabulary {
from : string;
to : string;
}
var vocabs : Vocabulary[];
非常感谢您的提示。
最佳答案
您可以使用 查找类型 引用接口(interface)子类型,这是在 TypeScript 2.1 中添加的:
interface ExerciseData {
id: number;
name: string;
vocabulary: Array<{
from: string;
to: string;
}>;
}
type Name = ExerciseData['name']; // string
这些查找类型也可以链接起来。因此,要获取词汇项的类型,您可以这样做:
type Vocabulary = ExerciseData['vocabulary'][number]; // { from: string; to: string; }
或者使用更多链接,from
字段:
type From = ExerciseData['vocabulary'][number]['from']; // string
对于复杂的场景,也可以将查找类型基于另一种类型。例如,在字符串文字联合类型上:
type Key = 'id' | 'name';
type FieldTypes = ExerciseData[Key]; // number | string
关于javascript - TypeScript:类型定义的引用子类型(接口(interface)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27875483/