类型 ‘X’ 到类型 ‘Y’ 的转换可能是 TS 中的错误

类型 ‘X’ 到类型 ‘Y’ 的转换在 TS 中可能是一个错误

Conversion of type ‘X’ to type ‘Y’ may be a mistake in TS

当我们对不兼容的类型使用类型断言时,会发生错误“将类型‘X’转换为类型‘Y’可能是一个错误,因为两种类型都没有充分重叠”。

要解决该错误,首先将类型加宽unknown,例如
myVar as unknown as MyType.

类型到类型的转换可能是错误的

下面是错误如何发生的示例。

索引.ts
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

索引.ts
const num = 5; const str: string = num as unknown as string;

我们将变量的类型扩大num
unknownunknown类型是 any 的类型安全对应物。

所有类型都可以分配给该unknown类型。

我们必须首先扩大类型,unknown因为类型的值number不能分配给类型的值string,反之亦然。

例如,如果 TypeScript 编译器认为变量可能是ornum类型,它会允许我们直接使用类型断言。numberstring

索引.ts
// 👇️ 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.

We are basically narrowing the type of the 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.

index.ts
// 👇️ const num: 42 const num = 42; // 👇️ const result: number const result = num as number;

The num variable has a literal type
of 42.

We are able to use a type assertion to widen its type to 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.

index.ts
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: