How do we prevent TypeScript from expanding a string literal type into a string?
E.g. in the Playground
type PropertyName = 'Property1' | 'Property2';
type ObjectWithPropertyName =
{ Property1: string; } |
{ Property2: string; };
const obj1: ObjectWithPropertyName = {
['Property1']: 'works',
}
const prop: PropertyName = 'Property1';
const obj2: ObjectWithPropertyName = {
[prop]: 'works',
}
const func = (prop: PropertyName) => {
const obj: ObjectWithPropertyName = {
[prop]: "fails",
};
};
const funcToo = (prop: PropertyName) => {
const propInner: PropertyName = prop;
const obj: ObjectWithPropertyName = {
[propInner]: "fails",
};
};
In the last case the error is this:
Property 'Property1' is missing in type '{ [x: string]: string; }' but required in type 'ObjectWithPropertyName'.
ObjectWithPropertyNamecan have onlyProperty1notProperty2aspropcould be.. Even if you fix this, the type will still be inferred to{ [x: string]: string; }. I don't think you will get away without a type assertion here..