Jez*_*Jez 2 javascript narrowing typescript type-narrowing
我有一个实用程序函数来检查变量是否为空或未定义,如果通过检查,我希望 TypeScript 缩小输入变量的范围,例如:
public init(input?: string): void {
function isSpecified(input: any): boolean {
return (typeof input !== "undefined") && (input !== null);
}
if (isSpecified(input)) {
let copiedString: string = input; // <-- Error; input is still 'string | undefined'
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的, TS 并没有消除字符串的可能性,undefined即使该函数在逻辑上是不可能的。有没有办法让这个函数调用缩小块input内的范围if?
您可以使用泛型类型保护函数:
public init(input?: string): void {
function isSpecified<T>(input: null | undefined | T): input is T {
return (typeof input !== "undefined") && (input !== null);
}
if (isSpecified(input)) {
let copiedString: string = input; // OK
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
247 次 |
| 最近记录: |