打字稿中特定类型的数组

时间:2017-02-15 20:44:56

标签: typescript

我在typescript中定义了一个特定类型的数组。分配与该类型不对应的值时,将根据需要生成错误消息。即使类型不正确, any 类型的分配仍然有效。

我是否误解了数组的类型定义?或者我是否低估了'#34; power" of anys: - )

这是一个简短的例子:

export class ItemList {

  items: Array<string> = [];

  constructor() {

    // push a string directly => works
    this.items.push('item 1');

    // push a string variable => works
    let item2:string = 'item 2';
    this.items.push(item2);

    // push a number variable => doesn't work
    let item3 = 3;
    this.items.push(item3);

    // push a number as any type => works
    let item4:any = 4;
    this.items.push(item4);

  }

}

let itemList = new ItemList();

来自tsc的错误是:

error TS2345: Argument of type 'number' is not assignable to parameter of type&#39; string&#39;。

有趣的是:plunkers在这里有用。

3 个答案:

答案 0 :(得分:5)

您要找的是union types

试试这个

items: (string|number)[]; // or...
items: Array<string|number>;

或者你可以像这样初始化它

items: (string|number)[] = ["Hello", 154]; // or...
items: Array<string|number> = ["Hello", 154];

答案 1 :(得分:1)

打字稿中特定类型的数组

ContentProviders

打字稿中任何类型的数组

if(message.content && message.content.toLowerCase() === 'xd') {
    message.reply("smh");
}

答案 2 :(得分:0)

  

我低估了任何人的“力量”

是的

any可分配给任何类型,因此即使itemsstring[]并且items.push()仅接受stringany也被接受。

  

但是最终我没有得到我期望的结果。

然后禁止anynoImplicitAnytsconfig条规则,no-anyno-unsafe-any条和tslint条规则。

从@artem的示例中可以看出,由于TypeScript does not control co- and contravariance of function parameters,其类型系统不能保证所需的类型安全性。