Skip to content

Can't index an object literal despite 'in' #61471

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
Sainan opened this issue Mar 23, 2025 · 3 comments
Closed

Can't index an object literal despite 'in' #61471

Sainan opened this issue Mar 23, 2025 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@Sainan
Copy link

Sainan commented Mar 23, 2025

πŸ”Ž Search Terms

index, object, literal

πŸ•— Version & Regression Information

Tried 5.8.2 and 5.9.0-dev.20250323

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.2#code/MYewdgzgLgBAJgQygmBeGBvAUDGAzEEALhgEYAaHGAIwQCcSAmLAXwG4stRJYBLMAA4BXKCWh1+AczQwARARCyOvPDAAU-YXzDwkCAJSYq3aDABuCADZCApiTBCAttRt0ZiZAG1NIgLodcExBLGwA6SxBJNQtrG30OFiwgA

πŸ’» Code

const data = {
  foo: 1,
  bar: 2
};

const input: string = "foo";
if (input in data) {
  const value: number = data[input];
  console.log(value);
}

πŸ™ Actual behavior

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: number; bar: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ foo: number; bar: number; }'.

πŸ™‚ Expected behavior

Indexing succeeds because in operator narrowed input to "foo" | "bar"

Additional information about the issue

I know that in the given example, data could simply be given a type of Record<string, number> but this is not an option when using JSON file imports.

@MartinJohns
Copy link
Contributor

Duplicate of #34867.

@jcalz
Copy link
Contributor

jcalz commented Mar 23, 2025

And #43284

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 24, 2025
@typescript-bot
Copy link
Collaborator

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

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Mar 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants