How can I hint to the Typescript compiler to infer string literal types for properties?

I think you’re looking for the const assertion, added in TS 3.4.

You just need to add as const to the string for it to become a literal type.

const x = {
    y: 'def' as const,
};

const z: { y: 'def' } = x; // no error :)

TS playground link

Leave a Comment