3 ms·
FWIW, Typescript is using Strategy 2: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABMOcAUEEBMawQLkSgCcQBTASkQG8AoRBxTMAZykQA8XEBeRAbQC6AbnqMuohgHop
by loevborg 7mo ago
FWIW, Typescript is using Strategy 2: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABMOcAUEEBMawQLkSgCcQBTASkQG8AoRBxTMAZykQA8XEBeRAbQC6AbnqMuohgHopiAHoB+WmIYxgiDNlzwwVFYwZcAdAAcQLABZoAjBUmMyAGxZl9B42ctoARAEN-3hTK7iz2MvJKAL5AA https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABM...
I'm a bit confused by the fact that the array starts out typed as `any[]` (e.g. if you hover over the declaration) but then, later on, the type gets refined to `(string | number)[]`. IMO it would be nicer if the declaration already showed the inferred type on hover.
- bastawhiz 7mo agoIt depends on your tsconfig. An empty array could be typed as never[], forcing you to annotate it.
- loevborg 7mo agoWhich setting specifically? Can you repro in the typescript playground?
- wk_end 7mo agoI don't believe this is correct. There's no settings that correspond to that AFAIK, and it'd actually be quite bad, because you could access the empty array and then get a `never` object, which you're not supposed to be able to do. https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABMOcAUBKAXIgzlAJxjAHNEBvAKEUQgX0TAFMA3Jg3HZtggbQF1EAXkQCA3NVr0oiAB7DGrdrl4AGfhJoEmUEASSyJAX0pA https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABM... `unknown[]` might be more appropriate as a default, but TypeScript does you one better: with OP's settings, although it's typed as `any[]`, it'll error out if you don't do anything to give it more information because of `noImplicitAny`.
- sheept 7mo agoI agree, it's always been unsettling to see any[] on hover, even though it gets typed in the end. I think one reason might be to allow the type to be refined differently in different code paths. For example: function x () { let arr = [] if (Math.random() < 0.5) { arr.push(0) return arr } else { arr.push('0') return arr } } In each branch, arr is typed as number[] and string[], respectively, and x's return type is number[] | string[]. If it decided to retroactively infer the type of arr at declaration, then I'd imagine x's return type would be the less specific (number | string)[].