I have a class Button, which implements IButton interface.
class Button implements IButton {
public fit = 'medium';
}
declare type Fit = 'small' | 'medium' | 'large';
export interface IButton {
fit: Fit;
}
I would expect to be able to assign medium as a default value to the fit property, but TypeScript throws an error when I try to do that.
Property 'fit' in type 'Button' is not assignable to the same property in base type 'IButton'.
Type 'string' is not assignable to type 'Fit'.
Is there a different way to archive this?
>Solution :
When you declare the variable as public fit = 'medium', TypeScript will infer the type of fit to be string. This does not match the interface IButtons‘s property fit which is of a narrower type.
You have multiple options to fix this:
- Declare the variable as
readonly
public readonly fit = 'medium'
- Use
as constoras Fit
public fit = 'medium' as Fit
//public fit = 'medium' as const
- Manually declare the correct type
public fit: Fit = 'medium'
Note: Only as Fit or the 3rd option will let you modify the value of fit during runtime.