为什么打字稿要求分配吸气剂?

时间:2020-07-27 19:12:04

标签: angular typescript

Typescript提示:“类型Test:testGetter中缺少以下属性”。

export interface ITest {
  id?: string | number;
  property: string;
}

export class Test implements ITest {
  id?: string | number;
  property: string;

  constructor(test?: Test) {
    Object.assign(this, test);
  }

  get testGetter() {
    return 1;
  }
}

1 个答案:

答案 0 :(得分:0)

您的接口将属性声明为字符串。但是,您无需在类中对其进行初始化,因此其真实类型为string|undefined

您可能拼错了界面吗?

初始化它,代码应该可以工作

export interface ITest {
  id?: string | number;
  property: string;
}

export class Test implements ITest {
  id?: string | number;
  property: string = '';

  constructor(test?: ITest) {
    Object.assign(this, test);
  }

  get testGetter() {
    return 1;
  }
}

new Test(new Test()) //compiles
new Test({ id: '1', property: '2' }) //compiles
相关问题