Azure 10923
Azure 10923

Reputation: 113

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,

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?

Upvotes: 0

Views: 2136

Answers (2)

michal pavlik
michal pavlik

Reputation: 348

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

Upvotes: 0

Quentin
Quentin

Reputation: 943080

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.

Upvotes: 1

Related Questions