Microsoft/TypeScript
GitHub で見るThe order of values in a union affects the correct type inference
Open
#59,729 opened on 2024年8月23日
Domain: check: Type InferenceHelp WantedPossible ImprovementUnion Order Dependence
Repository metrics
- Stars
- (48,455 stars)
- PR merge metrics
- (平均マージ 6d 17h) (30d で 9 merged PRs)
説明
🔎 Search Terms
union order type infer
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about union / order
⏯ Playground Link
💻 Code
type Message = { options?: Record<string, unknown> };
type Handler<T> = (message: T) => void;
declare function subscribe<T extends Message>(
payload:
| { message: T } & { handler: Handler<T> }
| { message: () => T } & { handler: Handler<T> }
): void;
subscribe({
message: () => ({ options: { market: 'market' } }),
handler: ({ options }) => {
// ^? Record<string, unknown>
},
});
🙁 Actual behavior
options type is Record<string, unknown>
🙂 Expected behavior
options type should be inferred as { market: string }
Additional information about the issue
if you reverse the order of values in the union:
declare function subscribe<T extends Message>(
payload:
| { message: () => T } & { handler: Handler<T> }
| { message: T } & { handler: Handler<T> }
): void;
then the type will be inferred correctly