我有一个实用程序函数来检查变量是否为null或未定义,并且我希望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'
}
}
正如您所看到的,TS并没有消除字符串为undefined
的可能性,即使该函数在逻辑上不可能。有没有办法可以调用此函数来缩小input
块内的if
范围?
答案 0 :(得分:4)
您可以使用通用类型保护功能:
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
}
}
答案 1 :(得分:2)
是的,您基本上只是在没有添加打字机的情况下编写了一个打字机功能。
变化:
goalItem.text
为:
function isSpecified(input: any): boolean
更一般地说,您可以使用相同内容的通用版本as mentioned by Ryan:
function isSpecified(input: any): input is string
答案 2 :(得分:0)
虽然在其他答案中建议的类型保护功能在许多情况下效果很好,但在这种情况下,您还有另一个更简单的选项。只需检查(typeof input !== "undefined") && (input !== null)
。
input != null
很容易忘记,有时由双等==
和!=
完成的类型转换实际上很有用:
function init(input?: string): void {
if (input != null) {
let copiedString: string = input; // <-- input is now 'string'
}
}
在javascript或打字稿中,以下都是true
:
undefined == null
null == null
'' != null