I need some help on my TypeScript adventure.
Here's my example type:
type Target = {
names: string[]
addresses: {
location: string
}[]
};
Here's my example object:
const myTarget: Target = {
names: ["Alex", "Nico"],
addresses: [
{
location: "Miami",
},
{
location: "New York",
},
],
};
And here's my function example:
const changeValue = (
key: keyof Target,
value: string | Record<string, unknown>
) => {
myTarget[key] = [...myTarget[key], value]
}
changeValue('names', 'Elvis')
changeValue('addresses', { location: "Atlanta" })
I've an error on the myTarget[key]
saying this:
Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[] & { location: string; }[]'.
Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[]'.
Cannot assign type 'string | Record<string, unknown>' of type 'string'.
Cannot assign type 'Record<string, unknown>' to type 'string' .ts(2322)
From what I understand is that, for example, TypeScript is testing all combinations, including adding an object to the names
array, which is invalid, or adding a string inside addresses
array.
Can someone please help me to understand what's the problem and how can I handle it. ( the real project is so much more complicated, but maybe with this example I'll understand a bit..)
Thanks a lot.