【问题标题】:How to cast inside .tsx file?如何在 .tsx 文件中进行转换?
【发布时间】: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


【解决方案1】:

如果您熟悉强类型语言中的类型转换,您可能会误解 as string 的作用。请记住,打字稿只存在于编译时,而不是运行时。所以as string 不会在运行时对数据进行任何更改,它只会影响在编译时评估事物的方式。 as string 是一种告诉 typescript “我比你更了解,所以不要在这里检查类型。假装它是一个字符串,即使所有证据都表明它是别的东西”。

有时需要使用类型断言,但只有在您确实知道 typescript 不知道的内容时才应该使用它。你得到这个错误的原因是它明显 不是 实际上是一个字符串,所以 typescript 添加了一个额外的层来说“你真的确定你不想让我检查你的类型吗?” .添加as unknown 表示“是的,真的不要检查我的类型”。

如果你想把它从一个数字变成一个字符串,不要使用类型断言;编写代码将其更改为其他类型:

let b : string = a.toString();
// or
let b : string = '' + a;

【讨论】:

  • 谢谢我习惯了弱类型语言,所以我现在在类型转换方面遇到了一些困难。我认为它能够在不使用 toString() 的情况下直接在字符串“2”中翻译数字 2。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2020-11-09
  • 2021-08-29
  • 2021-07-18
相关资源
最近更新 更多