I am trying to replace an object using SDK, and typescript throws the following error with the 'strict' mode on,
const offer = client.offer(oldOfferDefinition!.id);
await offer.replace(newOfferDefinition);
error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type '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?
CodePudding user response:
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.
CodePudding user response:
remove ! mark form oldOfferDefinition, and encapsulte this to condition
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