Why asignment is not accepted?
partnerAndDeliveryData2![key1] = {};
First parameter of the method key1
should be either "partnerData" or "deliveryData". But seems method signator implementation does not limits it, but intialize an array?!
import React, { useEffect, useState, Fragment } from "react";
export type SetPartnerAndDeliveryDataIn = {
partnerData?: NameAndAddress;
deliveryData?: NameAndAddress;
businessUseApproval?: boolean;
email?: string;
error?: string;
};
export type NameAndAddress = {
name?: string;
phoneNumber?: string;
country?: string;
postalCode?: string;
city?: string;
address?: string;
taxCode?: string;
};
export default function PartnerAndDeliveryForm(props: {}) {
const [partnerAndDeliveryData, setPartnerAndDeliveryData] =
useState<SetPartnerAndDeliveryDataIn>({
partnerData: {
country: "Magyarország",
},
});
const setData = (
key1: ["partnerData", "deliveryData"],
value: string
) => {
let partnerAndDeliveryData2 = {
...partnerAndDeliveryData,
};
partnerAndDeliveryData2![key1] = {};
}
}
CodePudding user response:
If you want the key1
parameter's type to be either the "partnerData"
or the "deliveryData"
string literal type, then you want it to be the union of those types, which is expressed via the |
operator:
key1: "partnerData" | "deliveryData" // union of string literals
Your current code is erroneously using a tuple type, which corresponds to an array of length 2, whose first element is "partnerData"
and whose second element is "deliveryData"
. That's not what you want:
key1: ["partnerData", "deliveryData"] // array of length 2
If you change key1
from a tuple to a union, things should start making more sense:
partnerAndDeliveryData2[key1] = {}; // okay