Home > Mobile >  TypeScript union type cannot be used as an array
TypeScript union type cannot be used as an array

Time:04-21

This is as far as I was able to reduce the problem to:

interface Word {
    value: string | string[];
}

const w: Word = {
    value: [] as string[] 
    // also tried: 
    // value: []
    // value: ['test']
}

w.value.push('')

The last line errors in my IDE because "push" does not exist for the type "string | string[]" (ts2339). It also wouldn't compile!

Is it a bug? Is it feature? How to help this?

CodePudding user response:

[] as string[] doesn't really do much in your code, since it's already clear from the usage that this array would be a string array, and you then assign the object to a Word. You've defined Word so that value can be either a string or a string array, and while you might have started off with an array, the type you defined says you might change it to a string on a different line of code. Since the value might not be an array, typescript won't let you push to it unless you first verify that it's an array.

For example:

if (Array.isArray(w.value)) {
  w.value.push('');
} else {
  w.value = [w.value, ''];
}

If you want w to be a narrower type, one that's similar to Word but guarantees that the value is always an array, then do this:

const w: Word & { value: string[] } = {
 value: []
}
  • Related