How To Solve Type ‘string’ is not assignable to type in TypeScript

In this article, we will explain what causes Type’ string’ is not assignable to type in TypeScript. The cause of this error is that we are trying to allocate a string value to a variable already defined by another data type. Let’s go into the specific situation and figure out how to fix it.

The cause of the error Type ‘string’ is not assignable to type in TypeScript.

When we are trying to allocate a string value to a variable already defined by another data type, the error occurs. Consider an example of an error below.

Error Example:

type Car = "Honda" | "Mercedes" | "Yamaha";
const myCar: string = "Mercedes";

// Allocate a string type to Car type
const myCollection: Car = myCar;

When we run the tsc command to compile this code, we get an Error.

Type 'string' is not assignable to type 'Car'.

The cause of the error is that the variable myCar is a string data type, while the variable myCollection has a data type of Car that we have declared before. When we assign myCar to myCollection then the error occurs. So how do we fix it?

Solution for error Type ‘string’ is not assignable to type in TypeScript.

Use Type Assertions

To solve this error, we use Type Assertions. In Typescript, type assertion is a technique to inform the compiler about the type of a variable. Type verification is similar to typing but will not restructure the code. You can use type assertions to specify the type of a value and tell the compiler not to infer it.

When we want to change a variable from one type to another, e.g., any variable is a number, we use type assertion. We can use <> braces or as keywords to do type-checking. Runtime support comes with style. At the same time, type-checking has no effect on runtime. It is used by the compiler.

Example:

type Car = "Honda" | "Mercedes" | "Yamaha";
const myCar: string = "Mercedes";

// Use Type Assertions convert string type to Car type
const myCollection: Car = myCar as Car;

We add the keyword as and the data type Car and the error is fixed.

Assert to const

Another way is to assert myCar to const, since TypeScript version 3.4 it’s possible to do that.

Example:

type Car = "Honda" | "Mercedes" | "Yamaha";

// Assert myCar to const
let myCar = "Mercedes" as const;
const myCollection: Car = myCar;

Summary:

So through this guide, you understand why this error appears. Please use Type Assertions to convert the data type to fix it. Hope you will quickly fix the error.

Leave a Reply

Your email address will not be published. Required fields are marked *