I have this:
let mp = {
transaction_amount: Number(data.amount_total),
description: 'signature',
payment_method_id: paymentType,
}
if (paymentType !== 'credit_card') {
mp.token = data.token
}
but typescript is saying token doesnt exist on type mp, how can I add the key 'token' there with its value?
CodePudding user response:
If you don't specify the type of an object, TypeScript will generate one implicitly when you create it. So you should specify the type of the object, and make the token optional.
type MP = {
transaction_amount: number;
description: string;
payment_method_id: whatever_payment_type_is;
token?: whatever_the_token_might_be;
};
let mp: MP = {
// etc
CodePudding user response:
It's not quite the same underlying runtime, but you can do
let mp = {
transaction_amount: Number(data.amount_total),
description: 'signature',
payment_method_id: paymentType,
token: paymentType !== 'credit_card' ? data.token : undefined
}
and still get the right types as long as you don't have strict requirements on the existence of the token
key.