简体   繁体   English

为什么 Typescript 要求分配 Getter?

[英]Why is Typescript asking to assign Getters?

Typescript prompts: 'is missing the following properties from type Test: testGetter'. Typescript 提示:'is missing the following properties from type 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;
  }
}

Your interface declares the property as a string.您的界面将属性声明为字符串。 However, you don't initialize it in the class so it's real type is string|undefined但是,您没有在 class 中对其进行初始化,因此它的真实类型是string|undefined

Might be you misspelled the interface?可能是你拼错了界面?

Initialize it and code should works初始化它,代码应该可以工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM