Dynamically add property name to typescript interface

I have a constant:

const name = 'some/property'; 

I would like to define an interface that uses the name as a key for a property in a similar way, using it in an object declaration as follows:

 {[name]: 'Bob'} 

I tried the following, but it looks like it is doing something else:

 interface MyInterface { [name]: string; } 

dynamically defines property names supported in typescript?

+5
source share
1 answer

You must specify a type name . There is no way to use it in the declaration of an object, but you can use [] to set and access the value of the property.

 interface MyInterface { [name: string]: string; } const n = 'qweq'; let x: MyInterface = { 'a': 'b' } x[n] = 'a'; 

And get access to this path.

 x[n] 

Check it out on the playground here .

+4
source

Source: https://habr.com/ru/post/1258601/


All Articles