Skip to content

Infer type from Array.some for value inside of if #47101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
5 tasks done
Gabriel-Alves-Cunha opened this issue Dec 10, 2021 · 0 comments
Closed
5 tasks done

Infer type from Array.some for value inside of if #47101

Gabriel-Alves-Cunha opened this issue Dec 10, 2021 · 0 comments

Comments

@Gabriel-Alves-Cunha
Copy link

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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant