Last updated: Feb 28, 2024
Reading timeยท3 min
The error "Conversion of type 'X' to type 'Y' may be a mistake because neither type sufficiently overlaps with the other" occurs when we use a type assertion with incompatible types.
To solve the error, widen the type to unknown
first, e.g.
myVar as unknown as MyType
.
Here is an example of how the error occurs.
const num = 5; // โ๏ธ Error: Conversion of type 'number' to type 'string' // may be a mistake because neither type sufficiently overlaps // with the other. If this was intentional, convert the //expression to 'unknown' first.ts(2352) const str: string = num as string;
The cause of the error is that the num
variable stores a value of type
number
, so we aren't allowed to use a
type assertion
with an incompatible type such as string
.
unknown
to solve the errorTo solve the error, widen the number's type to unknown
first and then narrow
it down to string
.
const num = 5; const str: string = num as unknown as string;
We widened the type of the num
variable to
unknown. The unknown
type is
the type-safe counterpart of any.
unknown
type.We had to widen the type to unknown
first because values of type number
and
not assignable to values of type string
and vice versa.
For example, if the TypeScript compiler thinks that the num
variable might be
of type number
or string
, it would allow us to use a type assertion
directly.
// ๐๏ธ const numOrStr: "bobbyhadz" | 100 const numOrStr = Math.random() > 0.5 ? 'bobbyhadz' : 100; // โ Works fine const str: string = numOrStr as string;
The numOrStr
variable might be a string or a number but we are still able to
use a type assertion with the string
type because the types string
and
string | number
overlap.
numOrStr
variable fromstring | number
to string
which is allowed because there is some overlap.Similarly, if you have a more specific value with a literal type, you are able to use a type assertion to widen its type.
// ๐๏ธ const num: 42 const num = 42; // ๐๏ธ const result: number const result = num as number;
The num
variable has a literal type
of 42
.
number
, because there is an overlap between the types (42
is a number).However, if there is no overlap between the types, we have to widen the type to
unknown
before we can use a type assertion to an incompatible type.
const num = 42; // ๐๏ธ const result: string const result = num as unknown as string;
Type assertions are used when we have information about the type of a value that TypeScript can't know about.
There are many valid use cases for widening a value's type to unknown
, so we
can use a type assertion with an incompatible type, e.g. incorrect typings of
third-party modules.
You can learn more about the related topics by checking out the following tutorials: