Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
    };
}
like image 934
heldt Avatar asked Sep 05 '17 09:09

heldt


People also ask

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .


1 Answers

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
        }
    };
}
like image 144
str Avatar answered Oct 11 '22 22:10

str