加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 属性’length’的类型是不兼容的.类型“4”不能分

发布时间:2020-12-17 18:01:44 所属栏目:安全 来源:网络整理
导读:我现在正在学习打字稿/角度,并且无法解决为什么TSLint将此作为错误抛出,但是代码本身可以在浏览器中工作和显示. export class GreetingComponent implements OnInit { names: [{ name: string }] = [{ name: 'Tom' },{ name: 'Dave' },{ name: 'Katie' },{ n
我现在正在学习打字稿/角度,并且无法解决为什么TSLint将此作为错误抛出,但是代码本身可以在浏览器中工作和显示.

export class GreetingComponent implements OnInit {

  names: [{ name: string }] = [{ name: 'Tom' },{ name: 'Dave' },{ name: 'Katie' },{ name: 'John' }];
  constructor() { }

  ngOnInit() {
  }

特别是这条线:

names: [{ name: string }] = [{ name: 'Tom' },{ name: 'John' }];

完全错误:

[ts]
Type '[{ name: string; },{ name: string; },{ name: string; }]' is not assignable to type '[{ name: string; }]'.
  Types of property 'length' are incompatible.
    Type '4' is not assignable to type '1'.
(property) GreetingComponent.names: [{
        name: string;
    }]

解决方法

类型:

[{name: string}]

是一个元素的tuple type.所以该类型只能是一个包含单个项目的数组.如果您希望该类型是一个填充了这些对象的任何长度的数组,那么它将被写为

{name: string}[]

// Or if you prefer:

Array<{name: string}>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读