Describe property object in TypeScript interface
There is nothing wrong with your first two examples. They both compile fine, and mean what they say.
In your third example, you apparently want the property name to be "dynamic". But remember, TS operates at compile time. At compile time, dynamicStrKey
has no value yet. Therefore, it is meaningless to try to use it as a property name in a type definition. You cannot define a compile-time artifact using a run-time value.
Finally, I think that my second variant was correct
interface ISome {
strProp:string;
complexProp:{
[someStrKeyWhichIsDynamic:string]:{
value:string;
optValue?:string;
}
};
}
For dynamic key you can just write [dynamic:string]
to specify that here will be some string property. Seems like I had webstorm error which wasn't related to the issue.
BTW, if you have some string based enum, you may want to use [key in MyEnum]: {...}
instead of [key:string]
. That solves error:
TS1337 an index signature parameter type can not be a union type.
And if you have a literal object, e.g.
const obj = { prop1: 'blah', prop2: 'blahblah' }
You may want to use [key in keyof typeof obj]: {...}
to describe that your dynamic key can be only 'prop1' or 'prop2' (or, more generic, value from Object.keys(obj
) )