heldt
heldt

Reputation: 4266

Property name on object from variable

Is there a way in typescript to set a property name from a variable?

Something like this

export function objectFactory(prop: string) {
    return {
        prop: {
            valid: false
        }
    };
}

Upvotes: 25

Views: 23573

Answers (2)

str
str

Reputation: 44969

You are looking for computed properties, this is an ES6 feature and not specific to TypeScript.

export function objectFactory(prop: string) {
    return {
        [prop]: {
            valid: false
        }
    };
}

Upvotes: 56

JSON Derulo
JSON Derulo

Reputation: 17536

You can do it like this:

export function objectFactory(prop: string) {
    let data: any = {};
    data[prop] = {};
    data[prop].valid = false;
    return data;
}

Upvotes: 5

Related Questions