export function isFunction(value: any): value is (...args: any[]) => any {
return typeof value === 'function';
}为什么使用value is (...args: any[]) => any而不是boolean?
发布于 2021-04-22 02:49:48
这被称为Type Guard,它为typescript提供了比运行时布尔检查更多的类型信息。https://medium.com/swlh/typescript-generics-and-type-guards-explained-by-example-177b4a654ef6
export function isFunctionTypeGuard(value: any): value is (...args: any[]) => any {
return typeof value === 'function';
}
export function isFunctionBool(value: any): boolean {
return typeof value === 'function';
}
const doSomething = (fn: any) => {
// using a runtime type check
if (isFunctionBool(fn)) {
fn(1, 2, 3);
// ^^ typescript still thinks the type is `any`
}
// using a typeguard
if (isFunctionTypeGuard(fn)) {
fn(1, 2, 3);
// ^^ typescript now knows the type is `(...args: any[]) => any`
}
}https://stackoverflow.com/questions/67201797
复制相似问题