如何分配字符串|在 TypeScript 中未定义为字符串? [英] How to assign string | undefined to string in TypeScript?
问题描述
我想分配一个变量,它是字符串 |未定义,到字符串变量,如您在此处看到的:
I want to assign a variable, which is string | undefined, to a string variable, as you see here:
private selectedSerialForReplace(): string | undefined {
return this.selectedSerials.pop();
}
luminaireReplaceLuminaire(params: { "serial": string; "newserial": string; }, options?: any): FetchArgs {
............
}
luminaireReplaceLuminaire({serial: this.selectedSerialForReplace(), newserial: response.output});
我收到此错误:
'{serial: string | 类型的参数不明确的;新闻:任何;}' 是不能分配给类型 '{serial":string; 的参数新闻":细绳;}'
Argument of type '{ serial: string | undefined; newserial: any; }' is not assignable to parameter of type '{ "serial": string; "newserial": string; }'
我无法更改 selectedSerialForReplace() 函数以返回任何其他内容.你能帮我吗?
I cannot change selectedSerialForReplace() function to return anything else. Could you please help me?
推荐答案
typescript 编译器执行严格的空检查,这意味着您不能传递 string |将 undefined
变量转换为需要 string
的方法.
The typescript compiler performs strict null checks, which means you can't pass a string | undefined
variable into a method that expects a string
.
要解决此问题,您必须在调用 luminaireReplaceLuminaire()
之前对 undefined
执行显式检查.
To fix this you have to perform an explicit check for undefined
before calling luminaireReplaceLuminaire()
.
在你的例子中:
private selectedSerialForReplace(): string | undefined {
return this.selectedSerials.pop();
}
luminaireReplaceLuminaire(params: { "serial": string; "newserial": string; }, options?: any): FetchArgs {
............
}
const serial = this.selectedSerialForReplace();
if(serial !== undefined) {
luminaireReplaceLuminaire({serial, newserial: response.output});
}
这篇关于如何分配字符串|在 TypeScript 中未定义为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!