我在.tsx文件中编写了一些代码,我需要转换一个变量,但是它不起作用,我也不明白为什么。
那是我的代码:
let a : number = 2;
let b : string = a as unknown as string;
console.log("b type = "+typeof(b))
结果就是:
b type = number
我认为这是因为我先转换为unknown,然后再转换为string,但我不知道为什么要这么做,但是如果我只写: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元素)
如果您熟悉强类型语言中的类型转换,则可能会误解as string
正在做什么。请记住,打字稿仅在编译时存在,而在运行时不存在。因此as string
不会在运行时对数据进行任何更改,只会影响在编译时如何评估事物。as string
这是一种告诉打字稿的方式,“我比你更了解,所以不要在这里检查类型。即使所有证据都说这是别的,也假装它是一个字符串”。
偶尔需要使用类型断言,但是只有在确实知道打字稿不需要的情况下,才应使用它。出现该错误的原因是,它显然不是字符串,因此很明显,所以打字稿增加了一层文字:“您确定要我不要检查您的类型吗?”。添加as unknown
说:“是的,真的不检查我的类型”。
如果要将其从数字转换为字符串,请不要使用类型断言。编写代码将其更改为其他类型:
let b : string = a.toString();
// or
let b : string = '' + a;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句