I have a constant:
const name = 'some/property';
I'd like to define an interface that uses name as a key for a property in a similar way to using it in an object declaration like so:
{[name]: 'Bob'}
I tried the following, but it seems that this is doing something else:
interface MyInterface {
[name]: string;
}
is dynamically defining property names supported in typescript?
To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional. Copied!
You have to specify the type of name. There's no way to use it in an object declaration but you can use the [ ] to set and access the property value.
interface MyInterface {
[name: string]: string;
}
const n = 'qweq';
let x: MyInterface = {
'a': 'b'
}
x[n] = 'a';
And access it this way.
x[n]
Check it out in the playground here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With