关于在 class 构造函数中使用默认道具的参数对象的打字稿菜鸟问题

Typescript noob question about having an parameter object with default props in class constructor

我有一个 javascript class 我想重写为 TS:

class A {
  constructor({foo = 'foo', bar = 123, baz = true} = {}) {
    this.foo = foo
    this.bar = bar
    this.baz = baz
  }
}

我目前在TS上写的内容:

interface AProps {
  foo: string,
  bar: number,
  baz: boolean,
}

class A {
  foo: string
  bar: number
  baz: boolean

  constructor({foo = 'foo', bar = 123, baz = true}: Partial<AProps> = {}) {
    this.foo = foo
    this.bar = bar
    this.baz = baz
  }
}

如你所见,typescript 的代码多了 3 倍,如何做到更紧凑? 据我所知,几乎所有代码重复都是反模式的,所以必须有办法告诉打字稿我想要来自该接口的 class 中的所有字段。

您无需指定 AProps 接口来提示构造函数的类型,它将被正确推断。

class A {
  foo: string
  bar: number
  baz: boolean

  constructor({foo = 'foo', bar = 123, baz = true} = {}) {
    this.foo = foo
    this.bar = bar
    this.baz = baz
  }
}

构造函数的类型:

constructor A({ foo, bar, baz }?: {
    foo?: string | undefined;
    bar?: number | undefined;
    baz?: boolean | undefined;
}): A

const a = new A({x: 1}); 编译失败并显示消息

Argument of type '{ x: number; }' is not assignable to parameter of type '{ foo?: string | undefined; bar?: number | undefined; baz?: boolean | undefined; }'.
  Object literal may only specify known properties, and 'x' does not exist in type '{ foo?: string | undefined; bar?: number | undefined; baz?: boolean | undefined; }'.(2345)

有原码

构造函数的类型:

constructor A({ foo, bar, baz }?: Partial<AProps>): A

const a = new A({x: 1}); 编译失败并显示消息

Argument of type '{ x: number; }' is not assignable to parameter of type 'Partial<AProps>'.
  Object literal may only specify known properties, and 'x' does not exist in type 'Partial<AProps>'.(2345)