【问题标题】:creating simple object in ts在 ts 中创建简单对象
【发布时间】:2017-11-01 20:18:51
【问题描述】:

我有界面

export interface Vehicle {
    IdNumber: number;    
    isNew: boolean;
    contact: { 
        firstName: string;
        lastName: string;
        cellPhoneNumber: number;            
    };
    color: string;
}

在组件内部我正在导入这个接口。

 let car: Vehicle = {
      IdNumber: 1,
      isNew: true,
      contact: {
        firstName: 'John',
        lastName: 'Doe',
        cellPhoneNumber: 123,            
      },
      color: 'red',          
    };

我无法编译这段代码导致 webpack 报以下错误

属性“联系人”的类型不兼容。

【问题讨论】:

  • AFAIK,您不能在 TS 接口中声明这样的子对象。见stackoverflow.com/a/42216124/3820185
  • 你可以。它在TypeScript playground 上编译得很好。
  • 为我工作。你用的是什么版本的 TS?
  • 完美运行。考虑直接使用 tsc --noEmit 进行类型检查,并告诉您与 Webpack 一起使用的任何 TypeScript 加载器不要进行类型检查。

标签: javascript typescript


【解决方案1】:

你有几个错误:

属性名称不匹配:

isExisting vs isNew // pick one...

类型错误:

color: red // 'red' needs quote marks to be a string

希望能解决这个问题...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多