如何解决如何在通用函数中引用“ typeof T”?
function isSameOrSubclass<T>(target:any,reference:typeof T):target is T
{
const targetIsReference = target===reference,targetIsTruthy = target&&true,targetHasPrototype = "prototype" in target,targetIsSubclass = targetIsTruthy&&targetHasPrototype&&(target.prototype instanceof reference)
return targetIsReference||targetIsSubclass;
}
编译器失败,出现以下错误:
TS2693:“ T”仅表示类型,但在此处用作值。
用typeof T
代替new()=>T
可以进行编译,但不允许这样做:
isSameOrSubclass<Class>(foo,Class)
因为
类型'typeof Class'的参数不能分配给'new()=> Class'类型的参数。
解决方法
T
必须限制为extends new() => {}
* 或类似的,然后直接使用(而不是通过typeof
使用),如下所示:
function isSameOrSubclass<T extends new() => {}>(target:any,reference: T):target is T
// −−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−^
{
const targetIsReference = target===reference,targetIsTruthy = target&&true,targetHasPrototype = "prototype" in target,targetIsSubclass = targetIsTruthy&&targetHasPrototype&&(target.prototype instanceof reference)
return targetIsReference||targetIsSubclass;
}
* 或类似的:类型new() => {}
指的是具有零参数构造函数的类。因此,要接受带有一个或多个参数构造函数的类,必须使用其他类型。即new(...args) => {}
然后使用它而不使用任何显式类型参数,例如:
class Parent {}
class Child extends Parent {}
class Unrelated {}
console.log(isSameOrSubclass(Child,Parent)); // true
console.log(isSameOrSubclass(Parent,Parent)); // true
console.log(isSameOrSubclass(Parent,Unrelated)); // false
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。