Background
Implementing this concept can be achieved in various ways. Here are some resources that discuss different approaches:
TypeScript: an interface property dependent on another
How to make Typescript interface property to be depended on another property
Typescript Interface - make type of one property dependent of type of another property
Approach
Through experimenting with different methods, I have found that the solution provided in the third link above is most suitable for my specific situation.
After testing various approaches, I realized that I had a particular question regarding this topic which warranted its own discussion.
Here is a snippet showcasing what I am working on:
enum MyEnum
{
One = 'One',
Two = 'Two',
Three = 'Three',
// And potentially more enums in the future.
}
interface MyInterface<T extends MyEnum>
{
prop1: string,
prop2: boolean,
prop3: T,
prop4: T extends MyEnum.One
? OneSpecificInterface
: T extends MyEnum.Two
? TwoSpecificInterface
: T extends MyEnum.Three
? ThreeSpecificInterface
: // And so forth.
}
prop3
can take any value from MyEnum
, and the type of prop4
depends on the value of prop3
.
For instance, if prop3
is MyEnum.One
, then the corresponding value passed to prop4
should be OneSpecificInterface
(an interface containing specific values for that data type).
The unique values within each prop4
may vary significantly, making it impractical to create a single encompassing interface. However, there needs to be a unified interface covering these four properties, leading me to this methodology.
Question
While the current solution works effectively, it's evident that as MyEnum
expands, the ternary operators within prop4
will become increasingly lengthy.
Is there a more concise or elegant approach to handle this logic within prop4
?
If a more streamlined method using the existing framework is not available, it's not a major setback since the current system is straightforward enough - however, I am still curious and haven't managed to find a conclusive answer independently yet.
I am open to exploring alternative types of type-checking that achieve the same outcome, but after attempting several options, I have determined that this method offers the best balance between readability and effectiveness.