Files
scriptc/tests/corpus/evolving-closure-array-derived.ts
T
Chris Tateandejc3 009a01d074 Type empty arrays filled by later writes inside functions by their reads
An unannotated `const xs = []` (or `let`) inside a function, which
TypeScript types by the elements written before each read, takes the array
type its settled reads have: records pushed in a loop give a record array,
numbers a number[], strings a string[]. Reads inside closures, which the
checker leaves unsettled, do not count. When settled reads disagree or the
binding is reassigned, the binding is a dynamic array, as the same binding
already is at module scope. Before, such a binding was always number[] and
pushes of other values were refused.

Fixes #1623

Co-authored-by: ejc3 <1694850+ejc3@users.noreply.github.com>
2026-10-21 02:40:20 -05:00

25 lines
806 B
TypeScript

// Derived values of an evolving-`any` closure array, at file scope and in
// a function body: slice and concat preserve the handle-element array
// (JS's IsArray decides concat's spread over the VALUE, not the evolved
// checker spelling), and the function-scope filter result adopts the
// handle-element type through the local declaration.
const fns = [];
fns.push(() => 1);
fns.push(() => 2);
fns.push(() => 3);
const tail = fns.slice(1);
console.log(tail.length);
tail.forEach(fn => console.log(fn()));
const both = fns.concat(tail);
console.log(both.length);
console.log(both.map(fn => fn()));
function pick(limit: number) {
const cbs = [];
cbs.push(() => limit);
cbs.push(() => limit * 2);
const kept = cbs.filter(fn => fn() > limit);
return kept.map(fn => fn());
}
console.log(pick(4));