close

[Solved] Typescript Type ‘string’ is not assignable to type

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Typescript Type ‘string’ is not assignable to type in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Typescript Type ‘string’ is not assignable to type Error Occurs?

Today I get the following error Typescript Type ‘string’ is not assignable to type in javascript.

How To Solve Typescript Type ‘string’ is not assignable to type Error ?

  1. How To Solve Typescript Type 'string' is not assignable to type Error ?

    To Solve Typescript Type 'string' is not assignable to type Error If you're casting to a dropdownvalue[] when mocking data for example, compose it as an array of objects with value and display properties.

  2. Typescript Type 'string' is not assignable to type

    To Solve Typescript Type 'string' is not assignable to type Error If you're casting to a dropdownvalue[] when mocking data for example, compose it as an array of objects with value and display properties.

Solution 1


When you do this:

export type Fruit = "Orange" | "Apple" | "Banana"

…you are creating a type called Fruit that can only contain the literals "Orange""Apple" and "Banana". This type extends String, hence it can be assigned to String. However, String does NOT extend "Orange" | "Apple" | "Banana", so it cannot be assigned to it. String is less specific. It can be any string.

When you do this:

export type Fruit = "Orange" | "Apple" | "Banana"

const myString = "Banana";

const myFruit: Fruit = myString;

…it works. Why? Because the actual type of myString in this example is "Banana". Yes, "Banana" is the type. It is extends String so it’s assignable to String. Additionally, a type extends a Union Type when it extends any of its components. In this case, "Banana", the type, extends "Orange" | "Apple" | "Banana" because it extends one of its components. Hence, "Banana" is assignable to "Orange" | "Apple" | "Banana" or Fruit.

Solution 2

If you’re casting to a dropdownvalue[] when mocking data for example, compose it as an array of objects with value and display properties.

example:

[{'value': 'test1', 'display1': 'test display'},{'value': 'test2', 'display': 'test display2'},]

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment