我怎样才能避免在 TypeScript 中使用对象名称 属性 和 this 关键字?

How could I avoid using the name of an object property along with the this keyword in TypeScript?

如何避免在 TypeScript 中使用对象名称 属性 和 this 关键字?

例如我可以写:

const foo = 2;
const bar = 3;
const baz = { foo, bar };

但我无法执行以下操作:

class A {
    foo: number = 2;
    bar: number = 3;
    f() {
        const baz = { this.foo, this.bar };
    }
}

如果您真的不喜欢任何重复,您可以自己编写一个辅助方法:

class A {
    foo: number = 2;
    bar: number = 3;
    f() {
        const baz = select(this, "foo", "bar")
    }
}

function select<T, K extends keyof T>(obj: T, ...props: Array<K>): Pick<T, K> {
    const copy = {} as Pick<T, K>;
    props.forEach(p => copy[p] = obj[p])
    return copy
}