'how to use auto convert of type detect in typescript when I use '=='
when I use '==' to judge equality between string and number,
const a = '1234';
const b = 1234;
// This condition will always return 'false' since the types 'string' and 'number' have no overlap.
const c = a == b;
typescript show an error: This condition will always return 'false' since the types 'string' and 'number' have no overlap.
but we kown the code works in javascript;
so is there any way to remove the error except using Number function to convert?
Solution 1:[1]
Using the equality operator (==) to compare two values which are known to be string and number by the compiler will always result in this error. You can either use a type assertion on one of the values, or use an abstraction to do the comparison (like the function in the example below):
function areEqual (a: unknown, b: unknown): boolean {
return a == b;
}
const a = '1234';
const b = 1234;
let c: boolean;
c = a == b; /*
~~~~~~
This condition will always return 'false' since the types 'string' and 'number' have no overlap.(2367) */
c = areEqual(a, b); // ok
c = a as unknown == b; // ok
However, if the compiler doesn't know for sure that the values are string and number, you won't have a problem with the direct comparison:
let a = '1234' as string | number;
let b = 1234 as string | number;
const c = a == b; // ok
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
