[英]Can I narrow this down in TypeScript?
我有一个实用程序函数来检查变量是否不为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
字符串的可能性。 有什么办法可以使此函数调用缩小if
块内的input
?
您可以使用通用类型保护功能:
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
}
}
是的,您基本上只编写了一个typeguard函数,而没有添加typeguard。
更改:
function isSpecified(input: any): boolean
至:
function isSpecified(input: any): input is string
更一般而言,您可以使用同一事物的通用版本, 如Ryan所述 :
function isSpecified<T>(input: null | undefined | T): input is T
尽管其他答案中建议的类型保护功能在许多情况下效果很好,但在这种情况下,您还有另一个更简单的选择。 而不是检查(typeof input !== "undefined") && (input !== null)
只是内联检查input != null
。
容易忘记,有时由double equal ==
和!=
进行的类型转换实际上可能是有用的:
function init(input?: string): void {
if (input != null) {
let copiedString: string = input; // <-- input is now 'string'
}
}
在javascript或打字稿中,以下各项均true
:
undefined == null
null == null
'' != null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.