Can the following structure be enforced with an index signature in TypeScript?
{
a: { name: 'a' }, // Valid
b: { name: 'b' }, // Valid
c: { name: 'd' } // Error: Type '"d"' is not assignable to type '"c"'.
}
This object allows any number of properties with string keys, but it requires that each property's value is an object with an optional 'name' property. The value of this 'name' property must match the key to which it is assigned in the parent object.
A similar outcome can be achieved using a string union type as shown below. However, extending this approach to accept keys as any string may pose a challenge.
type MethodNameVariant = 'GET' | 'PATCH' | 'POST' | 'DELETE';
type Methods =
{
[MethodName in MethodNameVariant]?: Method <MethodName>
};
interface Method
{
name?: MethodName;
}
Any assistance on this matter would be greatly appreciated!