TypeScript、泛型和 instanceof

时间:2021-02-24 16:15:44

标签: typescript inheritance assertion instanceof

我有以下代码:

abstract class BaseToken {}

class OpenParen extends BaseToken {
    public static assert(t: BaseToken): OpenParen {
        if (t instanceof OpenParen) {
            return t;
        } else {
            throw typeAssertionError;
        }
    }
}

class CloseParen extends BaseToken {
    public static assert(t: BaseToken): CloseParen {
        if (t instanceof CloseParen) {
            return t;
        } else {
            throw typeAssertionError;
        }
    }
}

assert 函数可用于检查给定的 BaseToken 实例是否实际上是它的特定特化。

const t: BaseToken = getTokenFromSomewhere();
const oparen = OpenParen.assert(t); // type of oparen is OpenParen, exception if not

因为除了 OpenParenCloseParen 派生自 BaseToken 之外,还有更多的类,这显然是很多样板。我想将 assert 的实现移到基类中。以下方法不起作用:

abstract class BaseToken {
    public static assert<T>(t: BaseToken): T {
        if (t instanceof T) { // T used as a value here
            return t;
        } else {
            throw typeAssertionError;
        }
    }
}

class OpenParen extends BaseToken {}
class CloseParen extends BaseToken {}

问题在于,一方面,这不会编译为 instanceof 需要一个值,而不是一个类,另一方面,这种方法不会将 T 绑定到子类类型,所以 OpenParen.assert 仍然是泛型。

我相信我可以在 C++ 中使用Curious recurring template pattern (CRTP) 实现这一点,但这在 TypeScript 中不起作用。有没有其他技巧可以做同样的事情?

3 个答案:

答案 0 :(得分:1)

编辑

有一个不需要实例的解决方案。它仍然没有您想要的确切语法,但至少这次达到了相同的效果。

Constructor 类型的积分为 https://www.simonholywell.com/post/typescript-constructor-type.html

type Constructor<T extends {} = {}> = new (...args: any[]) => T;

function isOfConstructor<T>(cns: Constructor<T>, b: BaseToken): b is T{
    return cns.prototype === b.constructor.prototype;
}

function assert<T>(cns: Constructor<T>, b: BaseToken) : T{
    if (isOfConstructor(cns, b)){
        return b;
    }
    else {
        throw new Error("not of that type");
    }
}

// then call it with
assert(OpenParen, getTokenFromSomewhere());

原始的“非静态”解决方案

如果您不需要 assert 是静态的,您可以使用

abstract class BaseToken{
    private hasSameTypeAs<T extends BaseToken>(t: BaseToken): t is T{
        return t.constructor.prototype === this.constructor.prototype;
    }

    public assert<T extends BaseToken>(t: T): T {
        if (this.hasSameTypeAs(t)) {
            return t;
        } else {
            throw new Error("foo");
        }
    }
}

答案 1 :(得分:1)

在静态方法中,this 应该引用当前正在使用的构造函数,因此实现应该只检查 t instanceof this

让打字工作更棘手。一个问题是静态方法没有polymorphic this;见microsoft/TypeScript#5863。您希望能够说 assert() 返回您正在调用它的构造函数的实例类型的值。对于 instance 方法,您可以说它返回名为 this... 的类型,但是对于静态方法没有类似的 this 类型。

不过,有一些解决方法。这是一种可能的方法:

abstract class BaseToken {
    public static assert<T extends BaseToken>(this: new (...args: any) => T, t: BaseToken): T {
        if (t instanceof this) {
            return t;
        } else {
            throw new Error("YOU DID A BAD THING");
        }
    }
}

这里我们使 assert 成为 generic 方法,其中类型参数 T 旨在成为正在使用的任何子类的实例类型。并且我们使用 this parameter 告诉编译器您只会在构造 assert() 实例的构造函数对象上调用 T


让我们测试一下:

class OpenParen extends BaseToken {
    someProp = 123;
}

class CloseParen extends BaseToken {
    otherProp = "abc";
}

const openP: BaseToken = new OpenParen();
const closeP: BaseToken = new CloseParen();

console.log(OpenParen.assert(openP).someProp.toFixed(2)); // 123.00
console.log(CloseParen.assert(closeP).otherProp.toUpperCase()) // ABC

openPcloseP 都只被编译器识别为 BaseToken,但 OpenParen.assert(openP)OpenParen.assert(closedP) 返回 OpenParen 和 {{ 1}},您可以访问我添加的特定于子类的属性,以证明这是有效的。

Playground link to code

答案 2 :(得分:0)

我不确定您是否可以在 TS 中执行此操作,因为大多数 TS 特定代码在转换为 JS 执行时都被删除了

在这里 [https://github.com/microsoft/TypeScript/issues/34516] 你可以看到现在抽象静态 bur 的提议 - 你需要稍微做一下。

现在我会将它添加到您的 BaseToken 类中

  public static assert<T>(t: T extends BaseToken<T>): T {
    throw new Error('[abstract BaseToken method .assert] called');
  };

PS:您的静态类执行非静态方法的想法在开始时会失败,即使对于您的想法,每个类至少需要一个空实例才能从静态类调用非静态方法。< /p>