Skip to content
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

[BUG]: TypeScript throws errors when adding [key: string]: string if other properties are not of type string #58194

Closed
RodrigoTomeES opened this issue Apr 15, 2024 · 2 comments

Comments

@RodrigoTomeES
Copy link

πŸ”Ž Search Terms

[key: string]: string override other types

πŸ•— Version & Regression Information

  • This is an error with types

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.5#code/C4TwDgpgBAKhDOwoF4oG8BQUrAcAXOlAK4BOANoYqQJYB2A5lAL4DcWUA2gNYQhXBajALoChDdmyA

πŸ’» Code

type Test = {
  test: { url: string };
  [key: string]: string;
};

πŸ™ Actual behavior

Throw error in test because is not a string

πŸ™‚ Expected behavior

Doesn't throw an error

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

MartinJohns commented Apr 15, 2024

This is working as intended. The type of the index signature must be at least a union including all types of the known properties. This is documented: https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

If you really want this, you can use an intersection type instead: { test: { url: string } } & { [key: string]: string }
But be aware that this is not sound. It's easy to still assign a string to the property test.

@RodrigoTomeES RodrigoTomeES closed this as not planned Won't fix, can't repro, duplicate, stale Apr 15, 2024
@fatcerberus
Copy link

To represent this type properly you'd need #17867

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

3 participants