14

I am using Angular 2 with TypeScript 2.

When I use

let labels: string[] | number[] = [];
// let labels: Array<number> | Array<string> = [];

labels.push(1);

it gives me error:

error TS2349: Cannot invoke an expression whose type lacks a call signature.

1 Answer 1

36

Changing

let labels: string[] | number[] = [];

to either of these

let labels: (string | number)[] = [];
let labels: Array<number|string> = [];

will solve the issue.

Sign up to request clarification or add additional context in comments.

2 Comments

I realize this is old, but figured I'd ask here anyway... I don't think string[] | number[] is equivalent to (string | number)[]. I think the first option means labels will be either an array of all strings, or an array of all numbers. While the second option means labels is an array whose contents can be strings or numbers, interchangeably. Any thoughts on that?
@austinbruch Yes, you're right. Here is more info: github.com/Microsoft/TypeScript/issues/10620. In that link, the same issue is happening to his code using filter because I imagine filter uses push under the covers. It makes sense that push doesn't work because: if labels is string[] rather than number[] than this code obviously wouldn't work: labels.push(1).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.