Imagine you have the following data:
const dataA = {
name: "John",
age: 25,
attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"},
}
const dataB = {
name: "Lisa",
age: 38,
attributes: {specificB: "hello", someMoreSpecificStuff: true, nonspecific:"Hope this"},
}
const dataC = {
name: "Peter",
age: 60,
attributes: {specificC: "hello", couldBeAnyName: "Oh My", nonspecific:"makes sense"},
}
Some components will only access basic information like name
and age
. Others will access general information as well as shared properties with different values (attributes.nonspecific
). Some components will exclusively work with one type of data.
To handle this, I have defined the following structure:
const dataA: MyDataType<A> = {
name: "John",
age: 25,
attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"},
}
const dataB: MyDataType<B> = {
name: "Lisa",
age: 38,
attributes: {specificB: "hello", someMoreSpecificStuff: true, nonspecific:"Hope this"},
}
const dataC:MyDataType<C> = {
name: "Peter",
age: 60,
attributes: {couldBeAnything: "Oh My", nonspecific:"makes sense"},
}
type MyDataType<T extends A | B | C> = {
name: string;
age: number;
attributes: T
}
type A = {
specificA: string;
specificA2: number;
nonspecific: string;
}
type B = {
specificB: string;
someMoreSpecificStuff: true;
nonspecific: string;
}
type C = {
couldBeAnything: string;
nonspecific: string;
}
While this approach works, it becomes cumbersome to specify all data types in every component:
interface ForMyGeneralComponent{
data: MyDataType<A | B | C>
}
It would be more desirable to use a generic type instead:
interface ForMyGeneralComponent{
data: MyDataType<GenericType>
}
and declare elsewhere that GenericType
can be either A
, B
, or C
.
This simplification would make the code more readable, especially when dealing with multiple data types.