Skip to content

using { [key]: value } doesn't resolve type properly when using union types. #56157

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
danielFHcode opened this issue Oct 19, 2023 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@danielFHcode
Copy link

πŸ”Ž Search Terms

"[key]", "key", "dynamic key"

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about the type inference of { [key]: value } objects.

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.0-beta#code/PQKgsAUASgpgzgewDYDd4AIAuCBckDek6x6AHjunJgE4CWAdgOYDckAvqxCMJAMYL0qZdAF50hCCXQBtAOSlZ6AIZx082QF0KsgHR7Z7SJFCRYiVBmx4IEqdPKUaDRlsd0mnNpACSgzDCUAE3QEADMsAAsYdBhSAAcYXn9A61sSe3QGNQUAH1kAT00KKndGQy4eCH4-dHzRcSJ09WVVdTzC1119dmYgA

πŸ’» Code

/*
Resolves to:
{
    x: string;
};
*/
const x = {
    ['x' as 'x']: '...'
}

/*
Resolves to:
{
    [x: string]: string;
}
Instead of the expected:
{
    [x in 'x'|'y']: string
}
*/
const y = {
    ['x' as 'x'|'y']: '...'
};

πŸ™ Actual behavior

In the first example ts works as expected, resolving the key with type 'x' to have a type of 'x'.
But in the second example, ts resolves the key with type 'x'|'y' to have a type of string.

πŸ™‚ Expected behavior

The expected behaviour was for the second example to work similarly to the first one, so that the key with type 'x'|'y' resolves to type 'x'|'y'.

Additional information about the issue

This has cause errors which seem to only be fixed with the as keyword - which I prefer not to use.

@jcalz
Copy link
Contributor

jcalz commented Oct 19, 2023

Duplicate of #13948, and note that [K in 'x'|'y']: string is equivalent to {x: string; y: string} and therefore not the type you actually want.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Oct 19, 2023
@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 Oct 22, 2023
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

4 participants