Currently, I have some Typescript Interfaces with repeated and similar fields. Here's an example:
interface Foo {
person1Name: string;
person1Address: string;
person2Name: string;
person2Address: string;
category: string;
department: string;
}
To streamline this structure, I attempted to utilize Typescript index signature templates by using [key: 'person${number}Name']
. However, my goal is to limit the number of allowable keys for 'person' properties to 5, which isn't functioning as intended.
type AllowedIndex = 1 | 2 | 3 | 4 | 5;
interface Foo {
[key: `person${AllowedIndex}Name`]: string;
[key: `person${AllowedIndex}Address`]: string;
category: string;
department: string;
}
Upon implementing the above code, I encountered the error message
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
.
Could anyone suggest a solution to achieve what I'm attempting to do? Or am I destined to repeat the keys in their current format?
For further reference, here is a TS Playground Link showcasing my attempts.