Typescript 原始类型:类型“数字"之间的任何差异;和“数字"(TSC 不区分大小写)? [英] Typescript primitive types: any difference between the types "number" and "Number" (is TSC case-insensitive)?

查看:16
本文介绍了Typescript 原始类型:类型“数字"之间的任何差异;和“数字"(TSC 不区分大小写)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个 number 类型的参数,但我拼错了类型,而是写了 Number.

I meant to write a parameter of type number, but I misspelled the type, writing Number instead.

在我的 IDE (JetBrains WebStorm) 上,类型 Number 用与原始类型 number 相同的颜色编写,而如果我写一个名称类(已知或未知)它使用不同的颜色,所以我猜它以某种方式将拼写错误的类型识别为正确/几乎正确/排序正确的类型.

On my IDE (JetBrains WebStorm) the type Number is written with the same color that is used for the primitive type number, while if I write a name of a class (known or unknown) it uses a different color, so I guess that somehow it recognizes the misspelled type as a correct/almost-correct/sort-of-correct type.

当我编译代码时,TSC 并没有抱怨编译器找不到名为 Number 的类,而是编写了以下错误消息:

When I compile the code, instead of complaining for example that the compiler couldn't found a class named Number, TSC writes this error message:

Illegal property access

这是否意味着 numberNumber 都以不同的类型共存?

Does that mean that number and Number both co-exists as different types?

如果这是真的,这些类之间的区别是什么?

If this is true, which is the difference between those classes?

如果不是这种情况,那么为什么它只是没有编写为未知类显示的相同错误消息(当前作用域中不存在名称'Number'")

If this is not the case, then why it simply didn't write the same error message it displays for unknown classes ("The name 'Number' does not exist in the current scope")

这是代码:

class Test
{
    private myArray:string[] = ["Jack", "Jill", "John", "Joe", "Jeff"];

    // THIS WORKS
    public getValue(index:number):string
    {
        return this.myArray[index];
    }

    // THIS DOESN'T WORK: ILLEGAL PROPERTY ACCESS
    public getAnotherValue(index:Number):string
    {
        return this.myArray[index]; 
    }
}

推荐答案

JavaScript 具有原始类型(数字、字符串等)和对象类型(数字、字符串等,它们在运行时显示).TypeScript 类型 numberNumber 分别指代它们.JavaScript 通常会将一个对象类型强制转换为其原始等价物,反之亦然:

JavaScript has the notion of primitive types (number, string, etc) and object types (Number, String, etc, which are manifest at runtime). TypeScript types number and Number refer to them, respectively. JavaScript will usually coerce an object type to its primitive equivalent, or vice versa:

var x = new Number(34);
> undefined
x
> Number {}
x + 1
> 35

TypeScript 类型系统规则是这样处理的(规范第 3.7 节):

The TypeScript type system rules deal with this (spec section 3.7) like this:

为了确定子类型、超类型和赋值兼容性关系、数字、布尔值和字符串原语类型被视为具有相同属性的对象类型分别为Number"、Boolean"和String"接口.

For purposes of determining subtype, supertype, and assignment compatibility relationships, the Number, Boolean, and String primitive types are treated as object types with the same properties as the ‘Number’, ‘Boolean’, and ‘String’ interfaces respectively.

这篇关于Typescript 原始类型:类型“数字"之间的任何差异;和“数字"(TSC 不区分大小写)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆