我有一个要重写为TS的javascript类:
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
}
}
如您所见,打字稿的代码多3倍,如何使它更紧凑?据我所知,几乎任何代码重复都是反模式的,因此必须有一种方法告诉打字稿我要从该接口获取类中的所有字段。
拒绝投票时,请至少在评论中写出问题出在哪里
您无需指定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)