首页 > 解决方案 > 使用打字稿声明类私有变量时是否可以使用解构?

问题描述

通常,当多个变量来自同一个对象时,我会使用

const [ foo, bar, foobar ] = [ 'foo', 'bar', 'foobar' ]

但是在类型脚本中,诸如

class Test {
    private {a,b,c} = tool;
}

它不再起作用了。

还有其他方法吗?

标签: javascripttypescriptecmascript-6

解决方案


您可以使用Object.assign来获得相同的结果...

class Test {
    private a: number;
    private b: string;
    private c: boolean;

    constructor(arg: { a: number, b: string, c: boolean}) {
        Object.assign(this, arg);
    }
}

const tool = {
    a: 5,
    b: 'str',
    c: true
}

const test = new Test(tool);

console.log(JSON.stringify(tool));

解构参数的功能仍在GitHub 上的讨论中活跃


推荐阅读