类型 ‘X’ 到类型 ‘Y’ 的转换在 TS 中可能是一个错误
Conversion of type ‘X’ to type ‘Y’ may be a mistake in TS
当我们对不兼容的类型使用类型断言时,会发生错误“将类型‘X’转换为类型‘Y’可能是一个错误,因为两种类型都没有充分重叠”。
要解决该错误,首先将类型加宽unknown
,例如
myVar as unknown as MyType
.
下面是错误如何发生的示例。
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;
错误的原因是num
变量存储了一个 type 的值
number
,所以我们不允许使用
不兼容类型的类型断言
,例如string
.
将类型加宽到unknown
解决错误
要解决该错误,请先将数字的类型扩大为unknown
,然后将其缩小为string
。
const num = 5; const str: string = num as unknown as string;
我们将变量的类型扩大num
到
unknown。该unknown
类型是 any 的类型安全对应物。
unknown
类型。我们必须首先扩大类型,unknown
因为类型的值number
不能分配给类型的值string
,反之亦然。
例如,如果 TypeScript 编译器认为变量可能是ornum
类型,它会允许我们直接使用类型断言。number
string
// 👇️ 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.
# Additional Resources
You can learn more about the related topics by checking out the following
tutorials:
- This comparison appears to be unintentional because the types ‘X’ and ‘Y’ have no overlap
- Allow only specific string values with TypeScript type
- Convert a Number to a String in TypeScript
- Convert a String to a Number in TypeScript
- 在 TypeScript 中将字符串转换为布尔值,反之亦然
- 如何在 TypeScript 中将对象转换为数组
- 如何在 Typescript 中将对象转换为 JSON 字符串
- 类型“X”与 TS 中的类型“Y”没有共同的属性