【问题标题】:What does the following syntax mean?以下语法是什么意思?
【发布时间】:2018-01-11 18:28:58
【问题描述】:

我看到这样的代码

export interface SmartType {
    type: string;
    [x: string]: any;
}
    

有人能解释一下最后一行,定义 x 的含义吗?

【问题讨论】:

  • x 是一个 any 类型的关联数组

标签: typescript interface


【解决方案1】:

这意味着SmartType 可以使用strings 进行索引,并且值的类型为any

interface SmartType {
    type: string;
    [x: string]: any;
}

let obj: SmartType = { type: 'Thing' };
obj['test'] = 'Hello World';
obj['test2'] = 10;
console.log(obj);

(jsFiddle)

打字稿手册在Interfaces: Indexable Types 部分解释了这一点。

【讨论】:

  • TypeScript 和 ES6 对 [ ] 在对象定义中的作用有冲突吗?
  • 不正确,SmartType 中没有 x 属性。 SmartType 的对象本身就是关联数组。
  • @KirillDmitrenko 我刚刚意识到并删除了它。
  • @zero298 我相信不同之处在于[ ] 中有一个类型,表明它是对象的索引定义。如果没有类型,它可能会尝试动态构造属性。我不确定,我从来没有使用方括号来动态构造任何东西。
【解决方案2】:

它没有定义x,它只是说SmartType 的对象可以用string 索引进行索引,并且存储在这些索引中的值的类型为any

const s: SmartType;
s['foo']; // -> any

x 只是一个名字,我想还有更多可以给键赋予含义。任何其他名称都不会改变该行的含义。

【讨论】:

    【解决方案3】:

    添加其他答案中未明确的内容。以下 TypeScript 接口:

    interface SmartType {
        type: string;
        [x: string]: any;
    }
    

    需要存在一个名为 type 的键,该键只接受 string 类型的值。

    然后它指定 any 其他键 可能strings 并且它们可能持有 any 类型的值。但是其他键也可以是数字

    type 可以容纳strings 的唯一原因是因为string 类型是any 类型(SmartType 接口中索引器的类型)的子集。

    这就是为什么除了必需的type 属性之外,您还可以在SmartType 类型的对象中添加任意数量的属性来保存任何类型的值。

    const someSmartValue: SmartType = {
        type: 'some text',
        whatever: {},
        anyOtherTextProperty: ['array', 'containing', 'whatever', 1000, true, {a: () => false}],
        2: () => 'OK'
    };
    

    Check it on TypeScript Playground

    将索引器的返回值更改为boolean 会导致定义无效:

    interface InvalidType {
        type: string; // [ts] Property 'type' of type 'string' is not assignable to string index type 'boolean'.
        [index: string]: boolean;
    }
    

    使用SmartType 接口,以下内容也是非法的,因为特别需要名为type 的键:

    const anotherSmartValue: SmartType = {
        someProp: {}
    }; // [ts] Type '{ someProp: {}; }' is not assignable to type 'SmartType'. Property 'type' is missing in type '{ someProp: {}; }'.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多