【问题标题】:Initializing Class properties in constructor call with destructuring使用解构初始化构造函数调用中的类属性
【发布时间】:2019-09-25 02:05:16
【问题描述】:

在 TypeScript 3.6.3 中,即使传递的对象符合适当的接口,我似乎也无法使用解构赋值来初始化构造函数中的类属性。有没有办法实现这一点,或者有很好的理由说明为什么不允许这样做?

interface TestInt {
    name: string,
    name2: string
}

class TestClass {
    name: string
    name2: string
  constructor(t: TestInt){   
    {this.name, this.name2} = t
  }
}

// static errors: 
// Property 'name' has no initializer and is not definitely assigned in the constructor.
// Property 'name' is used before being assigned.

let a = new TestClass({name: 'mom', name2:'dad'})
console.log(a.name)
console.log(a.name2)

// undefined
// undefined

【问题讨论】:

    标签: typescript


    【解决方案1】:

    解构工作正常;语句{name, name2} = t 定义或分配namet.namename2t.name2。但是,因为您指的是this.namethis.name2,所以Typescript 不会删除this. 并且无法执行分配。

    您可以在数组中看到这项工作:

    constructor(t: TestInt){   
      [this.name, this.name2] = [t.name, t.name2];
    }
    

    typescript playground

    你可以看到它使用详细的{name: this.name} 语法只要你给赋值加上括号。否则 Typescript 将大括号视为块,将name 视为标签。

    constructor(t: TestInt){   
      ({name: this.name, name2: this.name2} = t);
    }
    

    typescript playground

    尽管您可以使用Object.assignt 的属性分配给this,但Typescript does not correctly infer that all properties of TestClass are definitely assigned 即使我们假设t 的所有属性都按照定义存在。公平地说,如果t 仅通过其原型链包含namename2,这是不安全的。

    class Obj {
      get name() { return 'foo'; }   // compare with name = 'foo', noting "name" collision
    }
    
    class Obj2 extends Obj {
      get name2() { return 'baz'; }  // compare with name2 = 'bar'
    }
    
    let testClass = new TestClass(new Obj2());
    window.alert(`${testClass.name} ${testClass.name2}`);
    

    typescript playground

    相关:

    【讨论】:

    • 所以要使解构赋值起作用,完全限定的变量名称必须与右侧的完全匹配?
    • @Josh 是的,如果您希望语法在不使用冒号的情况下工作,您需要确切的 dict 键作为您的单个有效目标标识符。在链接到this ES6 discussion thread from March 2015this SO question 上对此进行了一些讨论(以及在设置特定属性时需要使用冒号)。
    猜你喜欢
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2013-04-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多