【问题标题】:TypeScript type checking on type rather than instance (part 2)TypeScript 类型检查类型而不是实例(第 2 部分)
【发布时间】: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);

Playground

那么我如何使用构造函数覆盖来维护类型检查?

附:我希望派生类型能够拥有私有或受保护的构造函数!

更新 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


【解决方案1】:

如果您将NumberMangler.constructor 设置为受保护,那么错误就会消失:

class NumberMangler extends Mangler<number> {
    protected constructor(
        public readonly item: number) {
        super(item);
    }
}

编辑

这应该可行:

class NumberMangler extends Mangler<number> {
    protected constructor(item: number);
    protected constructor(item: number, name: string);
    protected constructor(
        public readonly item: number,
        public readonly name?: string) {
        super(item);
    }
}

你并不真的需要非实现签名,但我认为它使它更具可读性。

【讨论】:

  • 感谢 Nitzan ...我玩了一些游戏,但很抱歉,我忽略了在我的问题中指出被覆盖的构造函数不能是多态的。查看我的更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
相关资源
最近更新 更多