Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property 'fit' in type Button' is not assignable to the same property in base type 'IButton'. Type 'string' is not assignable to type 'Fit'

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

  1. Declare the variable as readonly
public readonly fit = 'medium'
  1. Use as const or as Fit
public fit = 'medium' as Fit
//public fit = 'medium' as const
  1. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading