TypeScript中如何使用对象实例化JavaScript类?
解决TypeScript中通过对象实例化类的问题
嘿,我懂你遇上的麻烦了——你现在的构造函数是按位置顺序接收参数的,所以你传入的{bar: 'testing', z: 'test'}被直接当成第一个参数id赋值了,这完全不是你想要的结果对吧?
下面给你几个可行的实现方式,你可以根据自己的场景选最合适的:
方案1:重构构造函数为对象参数+默认值
直接把构造函数改成接收一个配置对象,配合TypeScript的Partial工具类型简化定义,再给可选属性设置默认值:
class Foo { public id: number; public bar: string; public y: number; public z: string; constructor(options: Partial<Foo> = {}) { // 给每个属性设置默认值,没传的话用默认值兜底 this.id = options.id ?? 0; this.bar = options.bar ?? ''; this.y = options.y ?? 0; this.z = options.z ?? ''; } } // 现在就能按你想要的方式实例化了 let x = new Foo({bar: 'testing', z: 'test'}); console.log(x.bar); // 'testing' console.log(x.z); // 'test' console.log(x.id); // 0(默认值)
如果某些属性是必填项,你可以去掉Partial,单独定义配置接口来明确必填/可选:
// 定义必填+可选的配置接口 interface FooConfig { bar: string; z: string; id?: number; y?: number; } class Foo { public id: number; public bar: string; public y: number; public z: string; constructor(config: FooConfig) { this.id = config.id ?? 0; this.bar = config.bar; this.y = config.y ?? 0; this.z = config.z; } }
这样TypeScript会强制你传入bar和z,避免漏传必填属性。
方案2:保留原构造函数,添加静态工厂方法
如果你不想改动原来的构造函数(比如要兼容旧代码),可以给类加一个静态工厂方法,让它接收对象参数来创建实例:
class Foo { constructor(public id: number = 0, public bar: string, public y: number = 0, public z: string) {} // 静态工厂方法,接收对象参数 static create(options: {bar: string; z: string; id?: number; y?: number}): Foo { return new Foo(options.id, options.bar, options.y, options.z); } } // 使用工厂方法实例化 let x = Foo.create({bar: 'testing', z: 'test'});
这个方案既保留了原有的参数顺序调用方式,又新增了你想要的对象参数调用方式,兼容性更好。
方案3:构造函数内直接解构对象参数
如果你的类属性不多,也可以直接在构造函数里用对象解构,同时给可选属性设置默认值:
class Foo { public id: number; public bar: string; public y: number; public z: string; constructor({id = 0, bar, y = 0, z}: {id?: number; bar: string; y?: number; z: string}) { this.id = id; this.bar = bar; this.y = y; this.z = z; } } // 实例化方式和你想要的一致 let x = new Foo({bar: 'testing', z: 'test'});
这种方式写法紧凑,一眼就能看到每个属性的默认值和必填项,适合属性较少的类。
内容的提问来源于stack exchange,提问作者Jeremy Thomas
相关产品推荐
相关产品推荐

