What's the right way to solve this?

<InputRow>
<Dropdown
title="Lora Name"
values={LoraNames.map((t) => ({ name: t, value: t }))}
value={lora_stack_item.name}
setValue={(value: z.infer<typeof LoraStackItem>["name"]) => {
const updatedLoraStack = [...efficiencyLoader.lora_stack.stack];
if (!updatedLoraStack[index]) return;
updatedLoraStack[index] = { ...updatedLoraStack[index], name: value };
setEfficiencyLoader({
...efficiencyLoader,
lora_stack: { ...efficiencyLoader.lora_stack, stack: updatedLoraStack },
});
}}
/>
</InputRow>
<InputRow>
<Dropdown
title="Lora Name"
values={LoraNames.map((t) => ({ name: t, value: t }))}
value={lora_stack_item.name}
setValue={(value: z.infer<typeof LoraStackItem>["name"]) => {
const updatedLoraStack = [...efficiencyLoader.lora_stack.stack];
if (!updatedLoraStack[index]) return;
updatedLoraStack[index] = { ...updatedLoraStack[index], name: value };
setEfficiencyLoader({
...efficiencyLoader,
lora_stack: { ...efficiencyLoader.lora_stack, stack: updatedLoraStack },
});
}}
/>
</InputRow>
Typescript error: updatedLoraStack[index] might be undefined, but we check it's not in the line before If I set updatedLoraStack[index] as a variable, check if its undefined and then set it, it won't update the original array
Solution:
just use ! to tell ts you're use it's there
Jump to solution
5 Replies
Josh
Josh12mo ago
unfortunately ts doesn't narrow array types like this properly
Solution
Josh
Josh12mo ago
just use ! to tell ts you're use it's there
sonor
sonorOP12mo ago
thx
Rhys
Rhys12mo ago
Extract it to a variable and check the variable as another option That lets you skip adding a !
sonor
sonorOP12mo ago
yea, but when I set that variable it wont affect the 1st array
let a = [1, 2, 3];
let b = [...a];
let q = b[2];
q = 5;
console.log(b); // [1, 2, 3]
let a = [1, 2, 3];
let b = [...a];
let q = b[2];
q = 5;
console.log(b); // [1, 2, 3]
for example^ and what i would need is [1, 5, 3] , but q = 5 only affects that original q value, and not the b array
Want results from more Discord servers?
Add your server