DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #19

Image description

Error Message: "X Is Not Assignable To Y"

In this article, we are looking at a user object and a UserProfile interface in TypeScript.

interface UserProfile {
    id: string;

    preferences: {
        theme: "light" | "dark";
    };
}

let user: UserProfile = {
    id: "123",
    preferences: {
        theme: "blue",
    },
};
Enter fullscreen mode Exit fullscreen mode

We will figure out how to resolve a type error:

Error Message: Type 'blue' is not assignable to type 'light' or 'dark'.
Enter fullscreen mode Exit fullscreen mode

👉 Understanding and Fixing 'Type Not Assignable' Errors

Let's investigate a common TypeScript error: "Type is not assignable"

Type 'blue' is not assignable to type 'light' or 'dark'.
Enter fullscreen mode Exit fullscreen mode

This error occurs when we try to pass a value (in this case, 'blue') into a slot that expects one of the types ('light' or 'dark').

Assignability is a crucial concept in TypeScript. It determines whether a value can be passed into a slot of a specific type or not. Let's look at a few ways to fix the error.

1️⃣ Pass a valid value: Replace 'blue' with either 'light' or 'dark'.

2️⃣ Add the new value to the type definition: Update the type to include 'blue':

type Theme = "light" | "dark" | "blue";
Enter fullscreen mode Exit fullscreen mode

Now, 'blue' is one of the members of the union, and it can be passed into the slot.

3️⃣ Widen the type definition: Change the type definition to accept any string:

type Theme = string;
Enter fullscreen mode Exit fullscreen mode

With this change, we can pass any string value, except for non-string types such as numbers:

Type 'number' is not assignable to type 'string'.
Enter fullscreen mode Exit fullscreen mode

Assignability errors occur when a value cannot be passed into a slot with a certain type.

For example, if TypeScript raises an error saying that "Type blue cannot be passed into a slot expecting light or dark", this means there is an assignability issue.

Understanding assignability can help you make sense of more complex errors that involve objects not being assignable to other objects.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)