【发布时间】:2021-02-03 10:33:32
【问题描述】:
我在 .tsx 文件中编写了一些代码,我需要转换一个变量,但它不起作用,我不明白为什么。
这是我的代码:
let a : number = 2;
let b : string = a as unknown as string;
console.log("b type = "+typeof(b))
这就是结果:
b type = number
我认为这是因为我先转换为未知数,然后转换为字符串,我不知道为什么它是必要的,但如果我只写:let b : string = a as string;,我会收到以下错误:
ERROR in App.tsx(59,22)
TS2352: 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.
那么有人知道如何在 .tsx 文件中进行转换吗? (不能使用 进行类型转换,否则它被视为 React 元素)
【问题讨论】:
-
那是如何在 .tsx 文件中转换(实际上是assert) - “当使用带有 JSX 的 TypeScript 时,只允许 as 样式的断言” 。
a as string在没有通过unknown的断言的情况下失败,因为a显然 不是 字符串。 -
您正在分配一个数字,但告诉编译器它将获得一个字符串,所有类型等都在编译期间被删除,使用
a.toString()或String(a)
标签: typescript react-native react-tsx