Closed
Description
TypeScript Version: 2.3
I have been trying to create a generic type that maps the property names and types from one type to a discriminated union of key value pair types. I have found that using a lookup across a mapped type works fine as long as you use a concrete type before doing the lookup (see pair2
below). But if you try to create a generic type alias to do the lookup you end up with a different result (see pair1
below).
Code
type Pairs<T> = {
[TKey in keyof T]: {
key: TKey;
value: T[TKey];
};
};
type Pair<T> = Pairs<T>[keyof T];
type FooBar = {
foo: string;
bar: number;
};
let pair1: Pair<FooBar> = {
key: "foo",
value: 3
}; // no compile error here
let pair2: Pairs<FooBar>[keyof FooBar] = {
key: "foo",
value: 3
}; // this does cause a compile error
Expected behavior:
Both pair1
and pair2
above should cause a compile error.
Actual behavior:
pair1
seems to be assigned the type:
{
key: "foo" | "bar";
value: string | number;
}
whereas pair2
is assigned the type I would expect:
{
key: "foo";
value: string;
} | {
key: "bar";
value: number
}