Skip to content

Object Indexing with a Template String #44675

New issue

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

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

Already on GitHub? # to your account

Closed
hbiede opened this issue Jun 20, 2021 · 2 comments Β· Fixed by #44512
Closed

Object Indexing with a Template String #44675

hbiede opened this issue Jun 20, 2021 · 2 comments Β· Fixed by #44512
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@hbiede
Copy link

hbiede commented Jun 20, 2021

Bug Report

πŸ”Ž Search Terms

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about it

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const fontSizes = {
  h1: 50,
  h2: 45,
  h3: 40,
  h4: 35,
  h5: 30,
  h6: 25,
}

type Props = {
  level: 1 | 2 | 3 | 4 | 5 | 6;
}

const getFontSizeForHeader = ({ level }: Props) => fontSizes[`h${level}`]; // error

console.log('Test', getFontSizeForHeader({ level: 1 }));

πŸ™ Actual behavior

When indexing an object with a template string, the template string is typed just as string instead of the proper union, causing an error and requiring a type cast or ts-ignore to rid.

πŸ™‚ Expected behavior

The template string typing to be used to check for valid indexing

@MartinJohns
Copy link
Contributor

I think you want #26797 / #44512.

@ahejlsberg
Copy link
Member

ahejlsberg commented Jun 20, 2021

With #44512 we will indeed give template literal types to template literal expressions in index positions. Meanwhile, it works with an explicit const assertion fontSizes[`h${level}` as const].

@ahejlsberg ahejlsberg self-assigned this Jun 20, 2021
@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Jun 20, 2021
@ahejlsberg ahejlsberg added this to the TypeScript 4.4.0 (Beta) milestone Jun 20, 2021
@typescript-bot typescript-bot added the Fix Available A PR has been opened for this issue label Jun 20, 2021
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants