为什么o1
型和o2
型的计算方式不同?
type MyUnion = 'foo' | 'bar' | 'baz';
type GenericData = { whatever: 'whatever' };
type FooData = { foo: 'foo' };
type BarData = { bar: 'bar' };
type BazData = { baz: 'baz' };
type MyData = {
foo: FooData;
bar: BarData;
baz: BazData;
}
const builders = {
foo: (_data: GenericData) => ({} as FooData),
bar: (_data: GenericData) => ({} as BarData),
baz: (_data: GenericData) => ({} as BazData),
};
type Returns = {
[Prop in keyof typeof builders]: ReturnType<typeof builders[Prop]>;
};
type Builders = {
[Prop in MyUnion]: (_data: GenericData) => Returns[Prop];
};
type Builders2 = {
[Prop in MyUnion]: (typeof builders)[Prop];
};
declare const d: GenericData;
function fn<T extends MyUnion>() {
const b1 = {} as Builders[T];
const b2 = {} as Builders2[T];
const o1 = b1(d);
// ^? const o1: Returns[T]
const o2 = b2(d);
// ^? const o2: FooData | BarData | BazData
}