The Typescript compiler will infer a string literal type for consts:
const a = 'abc';
const b: 'abc' = a; // okay, a is of type 'abc' rather than string
However, for properties, the type is inferred to be string
.
const x = {
y: 'def',
};
const z: { y: 'def' } = x; // error because x.y is of type string
In this example, how can I get the compiler to infer that x
is of type { y: 'def' }
without writing a type annotation for x
?
Edit: There's an open issue requesting support for this feature. One suggested workaround is to use syntax like this:
const x = new class {
readonly y: 'def';
};
const z: { readonly y: 'def' } = x; // Works
Try it in Playground here.
Edit 2: There's even an open PR that would solve this problem. Disabling type widening seems to be a popular request.