Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically adding a property name to a typescript interface

Tags:

typescript

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?

like image 877
Will Munn Avatar asked Oct 21 '16 11:10

Will Munn


People also ask

How do I add a property 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!

How do you dynamically access object property in TypeScript?

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] .

How do you assign values to objects in TypeScript?

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.

Can we have an interface with optional and default properties in TypeScript?

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!


1 Answers

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.

like image 114
toskv Avatar answered Oct 08 '22 10:10

toskv