英文:
typescript number returns string as typeof
问题
在代码中,我创建了一个名为 numericQuantity
的变量,它是一个被强制转换为数字类型的字符串 quantity
。有没有解释为什么在使用 typeof
运算符时,即使变量的类型为 :number
,它返回的结果仍然是 string?
let quantity: string = '10';
let numericQuantity: number = quantity as unknown as number;
console.log(typeof quantity); // string
console.log(typeof numericQuantity); //string
我在 TypeScript Playground 上尝试了这段代码,得到了相同的结果。
英文:
I created a numericQuantity
variable which is a casted string quantity
, is there an explanation why logging the typeof returns string even when the variable has a :number type?
let quantity: string = '10';
let numericQuantity: number = quantity as unknown as number;
console.log(typeof quantity); // string
console.log(typeof numericQuantity); //string
I tried this on the typescript playground and got the same result.
答案1
得分: 2
不要使用 quantity as unknown as number
,这只有在你知道代码是正确且有效的情况下才能满足 TypeScript 编译器,但类型系统不允许时才有帮助。
typeof
不是 TypeScript 运算符,它返回声明的类型。它是 JavaScript 运算符,返回运行时值的类型。而你的 numericQuantity
变量保存的是一个字符串。
如果你实际上想编写一个程序,将字符串值转换为数字值,而不是将 numericQuantity = quantity
,但要断言编译器“我知道得比你更好,这实际上是一个数字”,那么请这样写:
const quantity = '10';
const numericQuantity = Number(quantity);
console.log(typeof quantity); // string
console.log(typeof numericQuantity); // number
英文:
Don't use quantity as unknown as number
, that only helps to satisfy the typescript compiler when you know that code is correct and working but the type system won't allow it.
typeof
is not a typescript operator that returns the declared type. It's a javascript operator that returns the type of the runtime value. And your numericQuantity
variable holds a string.
If you actually want to write a program that converts the string value to a number value, instead of assigning numericQuantity = quantity
but asserting the compiler "I know better than you, this is actually a number", then write
const quantity = '10';
const numericQuantity = Number(quantity);
console.log(typeof quantity); // string
console.log(typeof numericQuantity); // number
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论