Skip to content

TypeScript is broken at type-checking array/Record access #54762

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
alamothe opened this issue Jun 24, 2023 · 3 comments
Closed

TypeScript is broken at type-checking array/Record access #54762

alamothe opened this issue Jun 24, 2023 · 3 comments
Labels
Unactionable There isn't something we can do with this issue

Comments

@alamothe
Copy link

alamothe commented Jun 24, 2023

const array = [1, 2, 3, 4]

a[i] // this should be of type number

type Key = "a" | "b" | "c"
const record: Record<Key, number> = { "a": 0, "b": 1, "c": 2 }

record[i] // this should be of type number

const record: Record<string, number> = { "a": 0, "b": 1, "c": 2 }

record[i] // this should be of type number | undefined

Why isn't there a way to configure TypeScript to have these most sane type assumptions? Either they're all a number, which is very unsafe for the third case, or with noUncheckedIndexedAccess they're all number | undefined which makes zero sense for the first two, as basically means to use ! for every array access.

EDIT: Note also that if Map is used in place of Record for the third case, it will correctly be number | undefined which also makes zero sense given that Record and Map are used interchangeably and should have consistent interfaces.

@alamothe alamothe changed the title TypeScript is terrible at type-checking array/Record index access TypeScript is broken at type-checking array/Record index access Jun 24, 2023
@alamothe alamothe changed the title TypeScript is broken at type-checking array/Record index access TypeScript is broken at type-checking array/Record access Jun 24, 2023
@MartinJohns
Copy link
Contributor

You forgot to fill out the issue template. The behavior is working as intended and not broken. Also, Record and Map are not interchangeably.

@RyanCavanaugh RyanCavanaugh added the Unactionable There isn't something we can do with this issue label Jun 26, 2023
@RyanCavanaugh
Copy link
Member

The statement here that numeric access should be assumed in-bounds and string access should be assumed possibly-out-of-bounds is actually the reverse from what I hear most often.

@typescript-bot
Copy link
Collaborator

This issue has been marked as "Unactionable" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Unactionable There isn't something we can do with this issue
Projects
None yet
Development

No branches or pull requests

4 participants