首页 > 解决方案 > 打字稿抱怨未分配 get 属性

问题描述

我有这个代码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

我收到以下错误

'{ id: number; 类型的参数 名称:字符串;}' 不可分配给“学生”类型的参数。类型“{ id: number;”中缺少属性“studentType” 名称:字符串;}'。

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

这是什么原因,我该如何解决?

附言。(我不想让它像 null 一样studentType?或将它转换为一个函数)

标签: javascripttypescript

解决方案


这是 TypeScript 中一个更有争议的话题。对于类,TypeScript 将类的整体形状视为类型。

这包括私有变量和方法,在这种情况下,包括 getter/setter。

您的问题的一种解决方案是您可以使用Partial<>

constructor(params: Partial<Student>) { ... }

或者Pick<>

constructor(params: Pick<Student, 'id' | 'name' | 'age'>) { ... }

另一种方法是自己创建一个接口:

interface IStudent { id: number, name: string, age?:number }
class Student implements IStudent {
  constructor(params: IStudent) { ... }
}

推荐阅读