javascript - Typescript 提示没有分配 get 属性

标签 javascript typescript

我有这个代码stackblitz

export class Student {
  id: number;
  name: string;
  age?:number;

  get studentType():string {
    return 'fullTime'
  }

  constructor(params: Student) {
    Object.assign(this, params);
  }
}

const student = new Student({id:1, name: 'Jon'}); //ts error here

我收到以下错误

Argument of type '{ id: number; name: string; }' is not assignable to parameter of type 'Student'. Property 'studentType' is missing in type '{ id: number; name: string; }'.

而studentType是一个只能获取的属性,不能设置。

这是什么原因以及如何解决?

ps。 (我不想像 studentType? 那样将其设置为可为空,或者将其转换为函数)

最佳答案

Getter/Setter 与常规属性完全相同,这就是为什么 Typescript 无法区分 getter/setter 和常规属性。不过,您可以将所有属性设为可选,这样您就可以省略 studentType:

  constructor(params: Partial<Student>) {
     Object.assign(this, params);
  }

但是,现在也可以省略其他属性(例如 name)。为了使类型更加安全,您可以引入一个附加接口(interface):

export interface StudentData {
  id: number;
  name: string;
  age?:number;
}

export class Student implements StudentData {
  get studentType():string {
    return 'fullTime'
  }

  constructor(params: StudentData) {
     Object.assign(this, params);
   }
 }

关于javascript - Typescript 提示没有分配 get 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585107/

相关文章:

javascript - jQuery Filtrify 插件 - 过滤 "or"而不是 "and"

javascript - 在 aws cloudfront 上部署一个 Angular 应用程序

TypeScript 不遵循代码逻辑 : Cannot invoke an object which is possibly 'undefined'

javascript - div中的li等间距用CSS或JS

Laravel 中的 JavaScript 本地化

typescript - 将枚举转换为自定义文字数组

forms - 如何获取嵌套 formBuilder 组的值

javascript - 在 ngFor 循环中选择变量键

javascript - c# 从 Angular 发送 3 个参数到 c#mvc,我在服务器端得到 null

javascript - 文本将成为 Div 背景的剪贴蒙版