Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类型脚本类型检查类型而不是实例(第2部分)_Typescript - Fatal编程技术网

Typescript 类型脚本类型检查类型而不是实例(第2部分)

Typescript 类型脚本类型检查类型而不是实例(第2部分),typescript,Typescript,第一部分提出了一个问题——TypeScript是否可以确保参数是给定类型或其派生类型,而不是类型或其派生类型的实例 第一部分中的解决方案是使用typeof关键字 范例 还是泛型 function giveMeAType<T extends typeof Foo>(type: T): void { } 如果将numberMagler.constructor设置为受保护,则错误将消失: class NumberMangler extends Mangler<number>

第一部分提出了一个问题——TypeScript是否可以确保参数是给定类型或其派生类型,而不是类型或其派生类型的实例

第一部分中的解决方案是使用typeof关键字

范例

还是泛型

function giveMeAType<T extends typeof Foo>(type: T): void {
}
如果将numberMagler.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…通过一点尝试,我解决了这个问题,但很抱歉,我忽略了在我的问题中指出重写的构造函数不能是多态的。请参阅我的更新。为了帮助解决多态构造函数问题,最好详细说明如何使用此Mangler。
class NumberMangler extends Mangler<number> {
    // This polymorphic constructor doesn't work.
    public constructor(
        public readonly item: number,
        public readonly name: string) {
        super(item);
    }
}
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);
    }
}