I am working on creating a function that can generate an array of numbers ranging from 0 to n, while ensuring that the returned type matches a known array structure at compile time.
const makeFoo = (n: number) => [...Array(n).keys()];
const foo1 = [0, 1, 2] as const; // readonly [0, 1, 2]
const foo2 = makeFoo(3); // number[]
console.log(foo1); // [0, 1, 2]
console.log(foo2); // [0, 1, 2]
Even though both foo1
and foo2
hold the same values, their types differ.
My question is, how can I define the return type of makeFoo
to match the structure of foo1
? (readonly [0, 1, ... n]
where the value of n
is also known statically, e.g.
makeFoo = <T extends number>(n: T) => ...
)