I
I
ivan05122020-02-23 16:23:26
typescript
ivan0512, 2020-02-23 16:23:26

Why is the empty array type never?

const test1 = []; // тут будет any[]
test1.push('');

const test2 = {
  field: [] // тут будет never[]
};
test2.field.push('') // соттветственно ошибка


Why is this happening? Why is an empty array given the type never when it's inside an object?
I know that you can fix the error if you explicitly set the type, but I want to figure out if this makes any sense or is it more of a typescript bug

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2020-02-24
@ivan0512

Here is the relevant bug. And here is an explanation why this is not a bug.
In general, an empty array is of type never[]. But in a simple case, TypeScript can infer the type of an initially empty array from subsequent operations on it. push type.
So actually the type test1 from your example will become string[]as soon as it is "fixed". For example, returned from a function or assigned to another variable.
So the following code will work:

function buildArray() {
  const test1 = []; // тут будет any[]
  test1.push('str');
  test1.push(1);
}
const array = buildArray(); // тип (string | number)[]

But this one is no more
const test1 = []; // тут будет any[]
test1.push('');
const test2 = test1;
test2.push(2); // Argument of type '2' is not assignable to parameter of type 'string'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question