typescript - 如何编写带 Partial 的类构造函数作为论据?
问题描述
我想编写一个以 Partial 作为参数的类构造函数。
下面是我的代码。
type UserInterface = {
username: string
passcode: number;
}
class User implements UserInterface {
username = 'Default username';
passcode = 1234
constructor(args: Partial<User>) {
for (const key in args) {
if (key in User) {
this[key as keyof this] = args[key as keyof typeof args];
}
}
}
}
但是 TypeScript 无法编译我的代码。
Type 'string | number | undefined' is not assignable to type 'this[keyof this]'.
Type 'undefined' is not assignable to type 'this[keyof this]'.
我错过了什么?
https://stackoverflow.com/a/52136787/14605338不是解决方案,因为它不验证类中是否存在属性。
解决方案
推荐阅读
- c# - 在 c 中读取和保存表单的位置
- angular - ASP.NET Core API / Angular - 身份验证问题
- javascript - TypeError: member is not a function when using `${member}`
- reactjs - 我没有让一个减速器记录我的状态更改
- c# - C# Azure CosmosDb 和 Mongo - 如何知道 Find 是否命中索引,以及针对这种情况的最佳索引建议是什么?
- javascript - 防ping系统。工作取决于哪个在上面
- scala - 在 scala 中是否有比 util.control.Breaks._ 更简单(要记住)的结构来进行中断?
- java - 在 Java 代码中使用 kotlin 扩展函数
- r - ggplot不能由R运行?
- python - 如何使用 python 修改给定的图网络以实现固定的平均度数?