TypeScript - 使用构造函数创建实例 属性
TypeScript - Create an instance using the constructor property
我想创建一个名为 createInstance
的函数,它接收一个实例 a
并创建一个与 a
类型相同的新实例 c
。注意createInstance
里面我不知道a
是什么类型,只知道是继承自classA
。但是我希望 c
是 B
类型,这是 a
的真实类型。这是我到目前为止得到的:
class A {
constructor(public ref: string) {}
}
class B extends A {
}
const createInstance = (a: A): void => {
const t = a.constructor
const c = new t("c")
console.log(c)
console.log(c instanceof B)
}
const b = new B("b")
createInstance(b)
我已经在 typescript playground 中尝试过它并且它有效,我得到 true
for c instanceof B
。但它在 new t("c")
行中显示警告,内容为:"This expression is not constructable. Type 'Function' has no construct signatures."
正确的做法是什么?谢谢
这实际上仍然是 TypeScript 中缺少的功能,因为 T.constructor
不是类型 T 而只是一个普通函数。你可以强制施放它:
const t = a.constructor as { new(ref: string): A };
编辑:您可以使用 ConstructorParameters
:
已经键入构造函数(参数列表)
const t = a.constructor as { new(...args: ConstructorParameters<typeof A>): A };
在 TS 存储库上查看相关问题#4536 and this
我想创建一个名为 createInstance
的函数,它接收一个实例 a
并创建一个与 a
类型相同的新实例 c
。注意createInstance
里面我不知道a
是什么类型,只知道是继承自classA
。但是我希望 c
是 B
类型,这是 a
的真实类型。这是我到目前为止得到的:
class A {
constructor(public ref: string) {}
}
class B extends A {
}
const createInstance = (a: A): void => {
const t = a.constructor
const c = new t("c")
console.log(c)
console.log(c instanceof B)
}
const b = new B("b")
createInstance(b)
我已经在 typescript playground 中尝试过它并且它有效,我得到 true
for c instanceof B
。但它在 new t("c")
行中显示警告,内容为:"This expression is not constructable. Type 'Function' has no construct signatures."
正确的做法是什么?谢谢
这实际上仍然是 TypeScript 中缺少的功能,因为 T.constructor
不是类型 T 而只是一个普通函数。你可以强制施放它:
const t = a.constructor as { new(ref: string): A };
编辑:您可以使用 ConstructorParameters
:
const t = a.constructor as { new(...args: ConstructorParameters<typeof A>): A };
在 TS 存储库上查看相关问题#4536 and this