Answer the question
In order to leave comments, you need to log in
Why is the empty array type never?
const test1 = []; // тут будет any[]
test1.push('');
const test2 = {
field: [] // тут будет never[]
};
test2.field.push('') // соттветственно ошибка
Answer the question
In order to leave comments, you need to log in
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)[]
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 questionAsk a Question
731 491 924 answers to any question