【发布时间】:2017-02-13 20:43:05
【问题描述】:
第一部分提出了一个问题——“TypeScript 是否可以确保参数属于给定类型或其派生类型,而不是类型或其派生类型的实例?”
TypeScript type checking on type rather than instance
第一部分的解决方案是使用 typeof 关键字
示例
function giveMeAType(type: typeof Foo): void {
}
或使用泛型
function giveMeAType<T extends typeof Foo>(type: T): void {
}
扩展这个解决方案,当将构造函数引入派生类型时,我遇到了一个新问题
class Mangler<T> {
protected constructor(
public readonly item: T) {
}
public static getManglers(mangler: typeof Mangler): typeof Mangler[] {
var whatever = [];
return whatever;
}
}
class StringMangler extends Mangler<string> {
// No constructor override here...
}
class NumberMangler extends Mangler<number> {
// But in this case, I need one...
private constructor(
public readonly item: number) {
super(item);
}
}
// This one works while StringMangler does not override the constructor.
Mangler.getManglers(StringMangler);
// But when I override the constructor, it doesn't work.
Mangler.getManglers(NumberMangler);
那么我如何使用构造函数覆盖来维护类型检查?
附:我希望派生类型能够拥有私有或受保护的构造函数!
更新 1
为了详细说明 Nitzan Tomer 的答案,我可以使构造函数protected,错误消失,但我不能使构造函数多态...
class NumberMangler extends Mangler<number> {
// This polymorphic constructor doesn't work.
public constructor(
public readonly item: number,
public readonly name: string) {
super(item);
}
}
【问题讨论】:
-
为了帮助解决“多态构造函数”问题,最好详细说明您打算如何使用这个
Mangler。
标签: typescript