首页 > 解决方案 > 如何编写带 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不是解决方案,因为它不验证类中是否存在属性。

标签: typescripttypescript-typings

解决方案


推荐阅读