Skip to content

Array.prototype.find not typing input as possibly undefined #49913

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
ChrisMcD1 opened this issue Jul 14, 2022 · 2 comments
Closed

Array.prototype.find not typing input as possibly undefined #49913

ChrisMcD1 opened this issue Jul 14, 2022 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@ChrisMcD1
Copy link

ChrisMcD1 commented Jul 14, 2022

Bug Report

πŸ”Ž Search Terms

Array, find, holes, sparse array

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Array.prototype.find

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Foo = {
  bar: number;
};

let arr: Array<Foo> = [];

arr[3] = {
  bar: 1,
};

const foundValue = arr.find((e) => e.bar === 1);

πŸ™ Actual behavior

TypeScript doesn't indicate that find has unique functionality among the Array.prototype methods in that it does not skip holes in an array. This seems to be intended behavior from what I have seen.

πŸ™‚ Expected behavior

TypeScript should mark that e could be of type Foo or undefined.

It doesn't make sense in my opinion to type arr as an Array<Foo | undefined> if it is known that you will never explicitly insert undefined into the array. Other javascript iterator functions like forEach will only go through the single defined element of arr, so the line arr.forEach((e) => e.bar ===1) would not throw a runtime exception. However, typing the array as Array<Foo | undefined> would result in a TypeScript error on that forEach statement.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jul 14, 2022
@RyanCavanaugh
Copy link
Member

TypeScript doesn't acknowledge the existence of sparse arrays; this particular function is only one of many which can get you into trouble. e.g. given the arr above, you could write for (const e of [...arr]) { e; } and have the same problem.

@ChrisMcD1
Copy link
Author

Oh, okay! Thank you for informing me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants