如何分配字符串| 在 TypeScript 中未定义为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45194964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign string | undefined to string in TypeScript?
提问by Sohrab
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});
I get this error:
我收到此错误:
Argument of type '{ serial: string | undefined; newserial: any; }' is not assignable to parameter of type '{ "serial": string; "newserial": string; }'
'{ 序列号:字符串 | 类型的参数 不明确的; 新闻:任何;}' 不能分配给类型 '{ "serial": string; 的参数 “新闻”:字符串;}'
I cannot change selectedSerialForReplace() function to return anything else. Could you please help me?
我无法更改 selectedSerialForReplace() 函数以返回任何其他内容。请你帮助我好吗?
回答by Acevail
The typescript compiler performs strict null checks, which means you can't pass a string | undefined
variable into a method that expects a string
.
打字稿编译器执行严格的空检查,这意味着您不能将string | undefined
变量传递给需要string
.
To fix this you have to perform an explicit check for undefined
before calling luminaireReplaceLuminaire()
.
要解决此问题,您必须undefined
在调用luminaireReplaceLuminaire()
.
In your example:
在你的例子中:
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});
}
回答by sschoof
If you are sure that serial could not be undefined
you can use the !
post-fix operator
如果您确定undefined
不能使用序列号,则可以使用!
post-fix 运算符
luminaireReplaceLuminaire({serial: this.selectedSerialForReplace()!, newserial: response.output});