Typescript:检查对象键和值是否适合当前类属性

pra*_*mil 1 types typescript

我需要检查对象键和值是否适合当前类属性。
我有类实例和单独对象中的更改,然后调用 Object.assign 来修改属性。有什么方法可以检查对象键和值对于特定类是否有效?

class MyClass {
  icon = 'home'
  size = 12
  color = 'blue'
}

var instance = new MyClass()

var changeProperties: MyClass = { size: 10 }
// throws Property 'icon' is missing in type { size: number; }

Object.assign(instance, changeProperties)
Run Code Online (Sandbox Code Playgroud)

现在出现未定义属性的错误(属性图标丢失)。

我尝试过var changeProperties: { [string: keyof MyClass]: any } = { size: true }但没有成功。

注意:我无法更改类本身(例如,使类属性可选)。

pra*_*mil 5

我在 lib.es6.d.ts 中找到了答案

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};
Run Code Online (Sandbox Code Playgroud)

所以答案是:

class MyClass {
  icon = 'home'
  size = 12
  color = 'blue'
}

var instance = new MyClass()

var changeProperties: Partial<MyClass> = { size: 10 }

Object.assign(instance, changeProperties)
Run Code Online (Sandbox Code Playgroud)