TypeScript、泛型和 instanceof
TypeScript, generics and 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
除了 OpenParen
和 CloseParen
从 BaseToken
派生的 class 之外,还有更多的 classes,这显然是很多样板。我想将 assert
的实现移到基础 class 中。以下不起作用:
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
需要一个值,而不是 class,另一方面,这种方法不会绑定 T
到 subclass 类型,所以 OpenParen.assert
仍然是通用的。
我相信我可以使用 Curiously recurring template pattern (CRTP) 在 C++ 中实现这一点,但这在 TypeScript 中不起作用。有没有其他技巧可以做同样的事情?
编辑
有一个不需要实例的解决方案。它仍然没有您想要的确切语法,但至少这次达到了同样的效果。
(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");
}
}
}
我不确定您是否可以在 TS 中执行此操作,因为大多数 TS 特定代码在转换为 JS 执行时已被删除
在这里 [https://github.com/microsoft/TypeScript/issues/34516] 你可以看到关于抽象静态 bur 的提议 - 你需要做一些事情。
现在我会将其添加到您的 BaseToken class
public static assert<T>(t: T extends BaseToken<T>): T {
throw new Error('[abstract BaseToken method .assert] called');
};
PS:你的静态 class 执行非静态方法的想法在开始时会失败,即使你的想法在那里你需要每个 class 至少一个空实例es 能够从静态方法调用非静态方法。
在静态方法中,this
应该引用当前正在使用的构造函数,因此实现应该只检查 t instanceof this
.
解决打字问题比较棘手。一个问题是没有 polymorphic this
for static methods; see microsoft/TypeScript#5863。您希望能够说 assert()
returns 是您正在调用它的构造函数的实例类型的值。对于 instance 方法,您可以说它 returns 名为 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 method where the type parameter T
is intended to be the instance type of whatever subclass is being used. And we are using a this
parameter 以告诉编译器您将仅在构造 T
实例的构造函数对象上调用 assert()
。
我们来测试一下:
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
openP
和 closeP
都只被编译器识别为 BaseToken
s,但是 OpenParen.assert(openP)
和 OpenParen.assert(closedP)
returns OpenParen
和 CloseParen
,您可以访问我添加的特定于子类的属性,以证明这是有效的。
我有以下代码:
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
除了 OpenParen
和 CloseParen
从 BaseToken
派生的 class 之外,还有更多的 classes,这显然是很多样板。我想将 assert
的实现移到基础 class 中。以下不起作用:
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
需要一个值,而不是 class,另一方面,这种方法不会绑定 T
到 subclass 类型,所以 OpenParen.assert
仍然是通用的。
我相信我可以使用 Curiously recurring template pattern (CRTP) 在 C++ 中实现这一点,但这在 TypeScript 中不起作用。有没有其他技巧可以做同样的事情?
编辑
有一个不需要实例的解决方案。它仍然没有您想要的确切语法,但至少这次达到了同样的效果。
(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");
}
}
}
我不确定您是否可以在 TS 中执行此操作,因为大多数 TS 特定代码在转换为 JS 执行时已被删除
在这里 [https://github.com/microsoft/TypeScript/issues/34516] 你可以看到关于抽象静态 bur 的提议 - 你需要做一些事情。
现在我会将其添加到您的 BaseToken class
public static assert<T>(t: T extends BaseToken<T>): T {
throw new Error('[abstract BaseToken method .assert] called');
};
PS:你的静态 class 执行非静态方法的想法在开始时会失败,即使你的想法在那里你需要每个 class 至少一个空实例es 能够从静态方法调用非静态方法。
在静态方法中,this
应该引用当前正在使用的构造函数,因此实现应该只检查 t instanceof this
.
解决打字问题比较棘手。一个问题是没有 polymorphic this
for static methods; see microsoft/TypeScript#5863。您希望能够说 assert()
returns 是您正在调用它的构造函数的实例类型的值。对于 instance 方法,您可以说它 returns 名为 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 method where the type parameter T
is intended to be the instance type of whatever subclass is being used. And we are using a this
parameter 以告诉编译器您将仅在构造 T
实例的构造函数对象上调用 assert()
。
我们来测试一下:
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
openP
和 closeP
都只被编译器识别为 BaseToken
s,但是 OpenParen.assert(openP)
和 OpenParen.assert(closedP)
returns OpenParen
和 CloseParen
,您可以访问我添加的特定于子类的属性,以证明这是有效的。