Search code examples
typescriptobjectpropertiesthisobject-literal

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


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

E.g. I can write:

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

But I can not do the following:

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

Solution

  • If you're really averse to any repetition at all you can write yourself a helper method:

    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
    }