Is there a preferred method for restricting a literal value in TypeScript to a specific type without sacrificing inferred type information?
Let's say we have a type Named
that must always contain a name.
type Named = {
name: string
};
If we use a type annotation, an error will be triggered for the additional field born
in the literal defining the constant cat1
.
const cat1: Named = {
name: 'Findus',
born: 1984, // this is an error
};
const name1 = cat1.name;
const born1 = cat1.born; // this is an error
When using a typecast, we can define the constant cat2
, but it loses type information for the field
born</code, making it challenging to access later.</p>
<pre class="lang-js"><code>const cat2 = {
name: 'Findus',
born: 1984,
} as Named;
const name2 = cat2.name;
const born2 = cat2.born; // this is an error
To address this issue, one approach is to employ an Immediately Invoked Function Expression (IIFE) to perform type checking on the literal when defining the constant cat3
.
const cat3 = (<C extends Named>(c: C) => c)({
name: 'Findus',
born: 1984,
});
const name3 = cat3.name;
const born3 = cat3.born;
Is this the recommended way to achieve constraint, or are there more effective alternatives for writing compatible code?