Closed as not planned
Description
π Search Terms
"union type as dynamic object key"
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Union types
β― Playground Link
π» Code
type Q = {
a?: string;
};
function qwop(t: 'a' | 'nope'): Q {
return {
[t]: 666, // this compiles
};
}
function qwop2(t: 'a'): Q {
return {
[t]: 666, // this gives type error as expected
};
}
type Q2 = {
[K in 'a' | 'b']?: string;
};
function qwop3(t: 'a'): Q2 {
return {
[t]: 666, // this gives type error as expected
};
}
function qwop4(t: 'a' | 'b'): Q2 {
return {
[t]: 666, // this compiles, bug?
};
}
type Q3 = {
a?: string;
b?: string;
};
function qwop5(t: 'a' | 'b'): Q3 {
return {
[t]: 666, // this compiles, bug?
};
}
π Actual behavior
Type check stops working when using a string union type as dynamic key to an object.
π Expected behavior
First I expected 'a' | 'nope'
to not be a valid type for key of { a?: string }
but I guess extraneous keys are just fine in a duck eat duck world.
What seems to be a bug to me is that the type declaration is ignored when the key type is a union - even when the full union is properly declared in the type. Ie. the type of properties 'a' | 'b'
is clearly string
and I expected a number
to produce a type error.
Additional information about the issue
No response