This condition will always return 'false' since the types '0' and '2' have no overlap

Viewed 1210

I am using vue class style component as following.

@Component()
export default class Transfer extends Vue {

  @Prop({ default: [] })
  buttonTexts!: [];
  
  get hasButtonTexts() {
    return this.buttonTexts.length === 2; // Here it gives error.
  }
  
}

and it shows error as below:

"This condition will always return 'false' since the types '0' and '2' have no overlap"

Is this a bug or I am doing something wrong here?

1 Answers

The problem is the type you're giving buttonTexts: []. That's an empty tuple, not (just) an array. Empty tuples always have a length of 0, and since length can't be any other number, the type of length is the literal type 0 rather than number (more below).

You almost certainly want buttonTexts to be an array of something. For instance, perhaps strings:

buttonTexts!: string[]

Playground link to pared-down code showing the issue.

Playground link to example fix.


So what's going on with this []? What's a tuple?

Basically, TypeScript lets you define types that are arrays with specific contents. For example: [string] is an array containing exactly one string. [string, number] is an array containing exactly two elements, the first one is a string, the second is a number. (This is handy for functions that return multiple things, like React's useState.) Similarly, [] is an array that contains nothing. So the type of its length property is the literal type 0, not number; the type of your 2 literal is the literal type 2; the error is there because the type 0 has no overlap with the type 2.

Related