Reputation: 1408
I am facing a strange error in typescript, which I couldn't find on the internet.
type IDialogTypeProps = 'info' | 'alert' | 'success' | 'warning';
interface IDialogProps {
text: string;
type: IDialogTypeProps;
}
const obj = {type: 'warning'}
const dialog:IDialogProps = {
text: 'string',
...obj,
}
Typescript throughs a warning about that
Types of property 'type' are incompatible. Type 'string' is not assignable to type 'IDialogTypeProps'
But when if I put type: string directly in the dialog object, typescript will compile without warnings. I am sure this is a pretty easy issue to solve.
Upvotes: 1
Views: 364
Reputation: 370609
The problem is that your obj
object, without being given an explicit type, is assumed by Typescript to be:
const obj: {
type: string;
}
You can force TS not to automatically widen the inferred type from 'warning'
to string
by denoting the 'warning'
string as const
. Change obj
's definition to:
const obj = { type: 'warning' as const }
Upvotes: 2