Sat Mar 19 2022·2 min read
Photo by Alice Rouse
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
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 - the
num variable stores a value of type
so we aren't allowed to use a
with an incompatible type such as
To solve the error, we have to widen the number's type to
unknown first and
then narrow it down to
const num = 5; const str: string = num as unknown as string;
We widened the type of the
num variable to
unknown type is the type-safe counterpart of any.
We had to widen the type to
unknown first, because values of type
not assignable to values of type
string and vice versa.
For example, if the TypeScript compiler thinks that the
num variable might be
string, it would allow us to use a type assertion
// 👇️ const numOrStr: "hello" | 100 const numOrStr = Math.random() > 0.5 ? 'hello' : 100; // ✅ Works fine const str: string = numOrStr as string;
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 | number overlap.
string | numberto
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;
num variable has a
number, because there is overlap between the types (
42is a number).
However if there is no overlap between the types, we have to widen the type to
unknown before we are able to 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.