[英]Argument of type 'string | undefined' is not assignable to parameter of type 'string'. typescript 'strict'
I am trying to replace an object using SDK, and typescript throws the following error with the 'strict' mode on,我正在尝试使用 SDK 替换 object,并且 typescript 在“严格”模式下引发以下错误,
const offer = client.offer(oldOfferDefinition!.id);
await offer.replace(newOfferDefinition);
error TS2345: Argument of type 'string |错误 TS2345:类型为“字符串”的参数 | undefined' is not assignable to parameter of type 'string'. undefined' 不能分配给'string' 类型的参数。 Type 'undefined' is not assignable to type 'string'.类型“未定义”不可分配给类型“字符串”。
const offer = client.offer(oldOfferDefinition!.id);
I am sure that oldOfferDefinition has id and it has a value, how can i get rid of this compliation error?我确信 oldOfferDefinition 有 id 并且它有一个值,我怎样才能摆脱这个编译错误?
If you are sure that it does, then throw an exception if it doesn't.如果您确定确实如此,则如果没有,则抛出异常。
const id = oldOfferDefinition!.id;
if (typeof id === "undefined") {
throw new Error("ID for old offer is undefined");
}
const offer = client.offer(id);
Since the runtime can't reach the line where you pass the value to offer
if that value is undefined, then the TS compiler will be happy with it.如果该值未定义,则运行时无法到达您传递要offer
的值的行,因此 TS 编译器会对此感到满意。
remove, mark form oldOfferDefinition, and encapsulte this to condition删除,标记形式 oldOfferDefinition,并将其封装到条件
if(oldOfferDefinition){
const offer: string = client.offer(oldOfferDefinition.id);
await offer.replace(newOfferDefinition);
}
but you should secure, that the result type of offer() function is defined as string但您应该确保,offer() function 的结果类型定义为字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.