【问题标题】:TypeScript: Reference subtype of type definition (interface)TypeScript:类型定义的引用子类型(接口)
【发布时间】:2015-01-10 11:03:27
【问题描述】:

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

非常感谢您的提示。

【问题讨论】:

  • 你是对的。你应该做你在最后一个代码块中所做的。
  • 谢谢@WayneEllery - 所以你会说这绝对不可能?
  • 是的。无论如何,你真的应该声明你的类型。

标签: javascript typescript typing


【解决方案1】:

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

【讨论】:

  • 有什么方法可以做到这一点?就像在 JS 中的 ExerciseData[xxx][]
  • 如果你想访问一个词汇的孩子,可以因此被链接起来吗?
  • @xperiments 我添加了一个基于另一种类型的查找类型的示例。如果使用动态你实际上意味着使用字符串值,那么不,这是不可能的,因为 TypeScript 编译器无法知道该值在运行时将是什么。
  • @Buts 是的,这是可能的。我在回答中添加了一个示例。
  • 谢谢,这个结果拯救了我的皮肤。
【解决方案2】:

这些天我发现它正在以另一种方式工作:

interface User {
  avatar: string;
}

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 嗯,这确实是一个非常有趣的可能性——尽管不是我想要的。谢谢你提到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2017-11-24
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多