建议:避免使用Function
只要有可能。它消除了类型安全性:
// these should error, but they don't
isDefined()
isDefined(1, 2, 3, 'too', 'many', 'args')
要保存类型签名,请删除Function
。也不妨使用!=
为了简单起见:
export const isDefined = (value: any): boolean => {
return value != null
}
作为奖励,您可以滥用泛型来使函数变得更智能。在这里,该函数使用generic https://www.typescriptlang.org/docs/handbook/generics.html T
推断传递给它的内容的类型,然后它使用类型保护 https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards在某些情况下缩小类型,例如一个 if 语句。 (注:我将其定义为function
让它发挥作用.tsx
文件。由于 JSX 的歧义,无法解析单通用箭头函数。)
export function isDefined<T>(value: T | null | undefined): value is T {
return value != null
}
declare const message: string | undefined
if (isDefined(message)) {
message // here, message is string
} else {
message // here, message is undefined
}