代码之家  ›  专栏  ›  技术社区  ›  chili83

Typescript:可以在类的私有属性中使用构造函数属性吗?

  •  1
  • chili83  · 技术社区  · 2 年前

    在变量中使用类的构造函数属性是否是错误的做法?我试过了,很惊讶 const name = new Name(time, course); 虽然我想这是有道理的,因为 Eng 需要创建这些构造函数属性,然后才能在其他地方使用它们。

    import { Name } from './Name'
    
    class Eng {
       private _name = new Name(time, course);
    
       private constructor(time: String, course: String) {} 
    
       method1(){
          let results = name.convertTrials();
    
          return results;
       }
    }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Alex Wayne    2 年前

    您的代码示例实际上存在类型错误:

    class Eng {
       private _name = new Name(time, course);
       // Cannot find name 'time'.(2304)
       // Cannot find name 'course'.(2304)
    
       private constructor(time: string, course: string) {} 
    }
    

    time course 就typescript而言,不在范围内。若要使用构造函数参数,它们必须位于构造函数主体中。


    可能让您困惑的是,在编译时,代码运行良好。这是因为非静态类属性为您移动到构造函数中,因为在普通JS中,它们需要在构造函数中。

    因此,编译后的类如下所示:

    // js
    class Eng {
        constructor(time, course) {
            this._name = new Name(time, course);
        }
    }
    

    这应该不会有问题。

    但是它 Typescript的一个问题,它认为构造函数参数不在构造函数之外的范围内。


    如果不需要参数:

    class Foo {
        constructor() {}
    }
    
    class UseFoo {
       private foo = new Foo()
       private constructor() {} 
    }
    

    那么你的方法就没有什么问题了。

    See Playground