javascript - 打字稿抱怨未分配 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?
或将它转换为一个函数)
解决方案
这是 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) { ... }
}
推荐阅读
- sorting - Julia 中的矩阵 - 排序和排序排列
- r - Create new columns based on comma-separated values in another column in R
- catboost - CatBoostClassifier - AUC metric
- python - 打字:如何将所有者类绑定到通用描述符?
- google-cloud-platform - GKE 监控,了解 Evictable 和 Non Evictable 内存
- javascript - 如果曾经单击过按钮,则运行一个函数,即使在页面重新加载时也是如此
- python - 如何根据其他事实从不同表中选择列以创建新的数据框python
- javascript - 将数据发送到 MySQL 数据库的 React/Node 错误
- mysql - 如何从触发器mysql中的select中获取值并将其用于IF条件
- flutter - 在 MacOS 中将私有 Flutter 项目存储库从 Github 克隆到 Xcode