我仍然不确定这个函数的真正需求是什么,但是让我们看看我们能做些什么。您需要在运行时为函数提供一个值,用于确定您是在检查字符串、数字还是其他内容。
假设第二个论点
typeGuard()
被称为
sentinel
,类型
Sentinel
,可以是构造函数,也可以是与
typeof
给你的。
type TypeofMap = {
string: string,
number: number,
boolean: boolean
}
type Sentinel = (new (...args: any[]) => any) | keyof TypeofMap;
然后,给定一个类型的值
哨兵
通过以下途径
conditional type
:
type GuardedType<T extends Sentinel> = T extends new (...args: any[]) => infer U ?
U : T extends keyof TypeofMap ? TypeofMap[T] : never;
你可以实现
这样地:
function typeGuard<T extends Sentinel>(value: any, sentinel: T): value is GuardedType<T> {
// assign to Sentinel instead of generic T to allow type guardingâ
const concreteSentinel: Sentinel = sentinel;
if (typeof concreteSentinel === "string") {
return typeof value === concreteSentinel;
} else {
return value instanceof concreteSentinel;
}
}
(见
Microsoft/TypeScript#13995
concreteSentinel
)
declare const thing: string | number | RegExp;
if (typeGuard(thing, "string")) {
console.log(thing.charAt(0));
} else if (typeGuard(thing, RegExp)) {
console.log(thing.flags);
} else {
console.log(thing.toFixed(0));
}
这有道理吗?