const record = {
foo: () => ({ foo: 1 }),
bar: () => ({ bar: 1 }),
}
function getRecord<T extends keyof typeof record>(type: T) {
return record[type];
}
const obj = getRecord(`foo`);
// if line 7 is: return record[type];
// typeof obj will be: () => { foo: number; }
// but if line 7 is: return record[type]();
// typeof obj will be: { foo: number; } | { bar: number; }
obj
When the return value is not called, TypeScript can successfully infer the return type to be () => { foo: number }, but when the return value is called, the type inference broadened to { foo: number; } | { bar: number; }. Why is this happening?
ReturnType<typeof record[T]>), like this