【发布时间】:2021-07-26 10:12:04
【问题描述】:
我正在尝试为父类是泛型的类族推断静态工厂方法的正确类型。我希望静态工厂方法的返回类型是父类以抽象两个子类,但 typescript 会推断出两个子类的一个或类型。
abstract class Parent<T> {
abstract readonly property: T
}
class ChildA implements Parent<string> {
constructor(readonly property: string) {}
}
class ChildB implements Parent<number> {
constructor(readonly property: number) {}
}
class Factory {
public static create(guard: any) /** I want to the return type be only Parent without indicate in a explicit way the generic **/ {
if (typeof guard === 'string') {
return new ChildA(guard)
}
if (typeof guard === 'number') {
return new ChildB(guard)
}
return new UnkwonClass()
}
}
我不知道如何描述工厂签名只返回 Parent 以抽象两个子类,因为两者将具有相同的形状,并且没有或类型 ChildA | ChildB
我尝试将签名写为 Parent,然后打字稿告诉我,Parent 是通用的,然后我将 create 方法的签名更改为 public static create<T>(guard: any): Parent<T> 但我必须从实例传递类型,然后我希望 ts 推断出我传递给子类的类型。
【问题讨论】:
-
请考虑修改此问题中的代码以构成minimal reproducible example,将其放入像The TypeScript Playground (link to code) 这样的独立IDE 时,可以清楚地说明您面临的问题。这将使那些想要帮助您的人立即着手解决问题,而无需首先重新创建它。它将使您得到的任何答案都可以针对定义明确的用例进行测试。
-
您可以将返回类型 注释 为您想要的任何类型,但我对示例代码的理解不足以知道该建议什么。你几乎肯定不想使用
Number或String类型,因为它们是很少使用的包装对象,而不是人们一直使用的number和string原语。guard应该是什么?它从何而来?ensureShouldBeA是什么?它从何而来?event是什么类型?你写了any,但它肯定不可能是任何东西,不是吗?你打算传递什么样的东西? -
我只是编辑帖子,我希望它得到更好的解释
标签: typescript oop types