TypeScript:类型定义的引用子类型(接口)

TypeScript: Reference subtype of type definition (interface)

我在我的 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[];

非常感谢您的提示。

不完全是您想要的,但您可以使用 typof 关键字解决这个问题,但前提是您有一个 var 声明为您的接口类型,如下所示。请注意,我认为您在上一个代码块中所做的要好得多:)

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

您可以使用 查找类型 引用接口子类型,在 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

我发现这几天它的工作方式如下:

interface User {
  avatar: string;
}

interface UserData {
  someAvatar: User['avatar'];
}

如果您不想导出所有内容,这非常有用。