Description
Suggestion
π Search Terms
Array.some
List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
I was coding and I came across this use-case demonstrated below. Shouldn't Typescript infer/narrow-down the type?
π Motivating Example
type Option = string; // Could be whatever else, `T`
type Allowed = "a" | "b" | "c" | "d" | "e" | "f";
const doSomething = (chosen: Allowed) => {};
const allowed = ["a", "b", "c", "d", "e", "f"] as const;
const chosenStr: Option = "a";
if (allowed.some(str => str === chosenStr))
doSomething(
chosenStr as Allowed,
// ^ I have to convert it here, but shouldn't Typescript
// know that chosenStr is one of `allowed`?
);
π» Use Cases
I guess this is more so we don't have to type the conversions. Also, such conversions means that there is no guarantee that such type is correct (narrowed down), making it possible to include values that aren't actually allowed at runtime; But if Typescript could accurately detect that the narrowed down type is allowed or not, the developer would know the constrains they wrote isn't enough.
Also, I saw that issue #46894 is alike, but it was said that this pattern doesn't appear enough to justify all the hard work. Therefor, I thought I'd open this issue too just to add to the list, :) π Maybe someday...