DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #26

Image description

Error Message: "Conversion Of Type X May Be A Mistake"

We have a Dog interface and a cat object.

The Dog interface is defined with a single boolean property bark:

interface Dog {
    bark: boolean;
}
Enter fullscreen mode Exit fullscreen mode

We also have a cat object whose property purr is set to true:

let cat = { purr: true };
Enter fullscreen mode Exit fullscreen mode

Dogs bark, and cats purr. So it makes sense that TypeScript gives us an error when trying to force the cat object into a Dog type:

let dog = cat as Dog; // red squiggly line under `cat as Dog`
Enter fullscreen mode Exit fullscreen mode

We get an error:

// Hovering over `cat as Dog` shows:

Conversion of type 'purr: boolean' to type 'Dog' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'bark' is missing in type 'purr: boolean' but required in type 'Dog'.
Enter fullscreen mode Exit fullscreen mode

In other words, there is a conflict because the Dog interface requires a bark property, while the cat object has a purr property.

We will figure out the root cause of this error and devise a way to fix it.

👉 Solution

TypeScript gives us an error when trying to convert a cat into a Dog because there is not sufficient overlap between the two types:

interface Dog {
    bark: boolean;
}

let cat = { purr: true };

let dog = cat as Dog; // red squiggly line under `cat as Dog`
Enter fullscreen mode Exit fullscreen mode

This warning message is like a request for confirmation from TypeScript. It is like TypeScript is asking if we are sure we want to perform this conversion.

We have a couple of ways to get around this error.

If we do not care about the consequences of converting one type into another, we can convert first to unknown or any before the target:

let dog = cat as unknown as Dog;

// or

let dog = cat as any as Dog;
Enter fullscreen mode Exit fullscreen mode

Using as is a common pattern, but in this case, it is actually unsafe because we are forcing the conversion even though properties are not shared. Depending on our linting settings, we may get a warning when using one or the other.

This workaround might lead to runtime errors, like when trying to access the property of bark, which does not exist in runtime. By performing this conversion, we are essentially deceiving TypeScript about the nature of our objects.

Resorting to as any as Dog might make the error message disappear, but it is not the best practice.

Think of this error as being a red flag that you should find a better way of modeling our application!


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

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

Top comments (0)