In my quest to create a unique generic type, I am experimenting with extracting property names and types from a given type to create a discriminated union type. Take for example:
type FooBar = {
foo: string;
bar: number;
};
This would translate to:
type FooBarPair = {
key: "foo",
value: string
} | {
key: "bar",
value: number
}
My initial approach looks like this:
type Pairs<T> = {
[TKey in keyof T]: {
key: TKey;
value: T[TKey];
};
};
type Pair<T> = Pairs<T>[keyof T];
However, when testing it with the aforementioned type:
let pair: Pair<FooBar> = {
key: "foo",
value: 3
};
I expected a compilation error but surprisingly there wasn't one. It turns out that the type of Pair<FooBar>
boils down to:
{
key: "foo" | "bar";
value: string | number;
}
While I suspect this could be a bug within TypeScript, I'm open to exploring alternative approaches to achieve the desired outcome.