【问题标题】:TypeScript constructor type safeTypeScript 构造函数类型安全
【发布时间】:2016-03-14 15:25:58
【问题描述】:

为什么当变量 id 被声明为数字时,下面的代码编译得很好,而在构造函数中它被分配了一个字符串?

interface IComplexType{
    id: number;
    name: string;
}

class ComplexType implements IComplexType{
    id: number;
    name: string;
    constructor(idArg: number, nameArg: string);
    constructor(idArg: string, nameArg: string);
    constructor(idArg: any, nameArg: any){
        this.id = idArg;
        this.name = nameArg;
    }

}

window.onload = () =>{
    var complexType: ComplexType = new ComplexType("hi","hi");
    console.log(complexType.id);

}

谢谢!

【问题讨论】:

    标签: javascript types constructor typescript


    【解决方案1】:

    简短的回答...因为它没有被分配一个字符串,它被分配了一个any类型的变量。

    this.id = idArg;
    

    any 类型表示该值“可以被视为任何类型”。因此,当编译器询问“我可以将any 分配给number”时,答案是“是”。

    您可以使用联合类型缩小构造函数中的类型(并消除重载,这总是一件好事):

    class ComplexType implements IComplexType{
        id: number;
        name: string;
        constructor(idArg: string | number, nameArg: string){
            this.id = idArg;
            this.name = nameArg;
        }
    }
    

    这有一个额外的好处是告诉您分配是一个可能的错误,这将迫使您更新签名(要么解析字符串中的数字,要么在提供字符串时执行您想要的任何操作)。

    例子的关键部分是string | number,表示类型要么是字符串要么是数字,比any限制更多。

    【讨论】:

      【解决方案2】:

      Typescript 编译成 JavaScript,实际上不支持函数重载。重载声明仅在编译期间用于类型检查。

      这个构造函数

      constructor(idArg: any, nameArg: any){
          this.id = idArg;
          this.name = nameArg;
      }
      

      允许传递任何类型的参数,因此允许使用字符串。

      在构造函数内部传递的值被分配给类属性。并且在此操作期间没有发生类型转换 - 因为这是 JavaScript。

      您可以找到“TypeScript 中的构造函数重载”并查找例如this 以了解更多详细信息和可能的解决方案。

      【讨论】:

        猜你喜欢
        • 2019-02-03
        • 2022-06-25
        • 2021-02-07
        • 1970-01-01
        • 2019-05-26
        • 2016-08-21
        • 1970-01-01
        • 1970-01-01
        • 2019-07-17
        相关资源
        最近更新 更多