Home > Software design >  Type is not assignable to type - ts(2416)
Type is not assignable to type - ts(2416)

Time:12-31

I have the following interface and type (simplified):

type MyOwnColorType = "red" | "blue";

interface Title {
  id: string;
  color: MyOwnColorType;
}

export interface Example {
  title: Title;
}

If i try to create a class using this interface it will throw the ts 2416 error:

class JustAExample implements Example {  
  title = {
    id: "value",
    color: "red",
  }
}

It works if i cast it but that kind of defeats the purpose:

class JustAExample implements Example {  
  title = {
    id: "value",
    color: "red" as MyOwnColorType,
  }
}

Normally I would just state the type but considering it's a literal object I honestly just don't know the syntax for it. If I would put in a number for the id field it would state that wrong value is used so it does work as intended.

How can I make sure that the color is the given type?

CodePudding user response:

To specify the type of the color property in the object that you are assigning to the title property of your JustAExample class

You can use type annotation or type assertion to specify the type of the color property

Like this

class JustAExample implements Example {  
  title: Title = {
    id: "value",
    color: "red",
  }
}

OR

class JustAExample implements Example {  
  title = {
    id: "value",
    color: "red",
  } as Title;
}

TS PlayGround

  • Related