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

问题描述 投票:0回答:4

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

非常感谢您的提示。

javascript typescript typing
4个回答
108
投票

您可以使用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

8
投票

我发现这些天它正在以下面的方式工作:

interface User {
  avatar: string;
}

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

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


7
投票

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

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

0
投票

如果您尝试通过

Interface['index']
访问,但
index
可能是
undefined
(可选),请记住一些事情。

注意下面的

?

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

像这样使用

NonNullable
实用程序类型...

type Test = {
    prop: NonNullable<ExerciseData['vocabulary']>[number]['from']
}
© www.soinside.com 2019 - 2024. All rights reserved.