0

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?

2
  • I'd actually just make this always string[] to avoid things like this. Commented Apr 20, 2022 at 15:04
  • It's not a bug, but "how to help this" depends on your use case. By annotating w as being of type Word, the compiler gives w that type. Even though you initialize w.value to string[], the compiler does not narrow w to {value: string[]} upon assignment. See ms/TS#33205. Personally I'd just not annotate w at all and let the compiler infer it as {value: string[]} to begin with. Commented Apr 20, 2022 at 15:17

1 Answer 1

1

[] 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: []
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.