From e602894f50435b8cd62096d4823b40daa8822d1a Mon Sep 17 00:00:00 2001 From: Brian Schiller Date: Thu, 5 Sep 2024 09:57:41 -0700 Subject: [PATCH] Fix Event.emit type error for enums MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rust enums are represented in TS as a type union. For some reason, `T extends null` collapses the type into an intersection, which makes it a type error to call `SomeEvent.emit(x)` for any value x. Here's a minimal example to try in the typescript playground. The definition of __EventObj__ is as it is *before* my patch. ```ts // These definitions come from @tauri-apps/api/event interface Event { /** Event name */ event: EventName; /** Event identifier used to unlisten */ id: number; /** Event payload */ payload: T; } declare function emit(event: string, payload?: unknown): Promise; type EventCallback = (event: Event) => void; type EventName = string & Record // This is generated by tauri-specta based on my rust types export type SocketAction = | { MessageForClient: { conn_id: string; message: string } } | { CloseSocket: { conn_id: string } } // This is also from tauri-specta, but doesn't depend on my types type __EventObj__ = { emit: T extends null ? (payload?: T) => ReturnType : (payload: T) => ReturnType } // pretend we have one of these declare const eo: __EventObj__; const x = { MessageForClient: { conn_id: 'string', message: 'str' }} satisfies SocketAction eo.emit(x) // 💥 Type error ``` --- examples/app/src/bindings.ts | 2 +- src/lang/globals.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/app/src/bindings.ts b/examples/app/src/bindings.ts index 3ec8f4c..5b4519c 100644 --- a/examples/app/src/bindings.ts +++ b/examples/app/src/bindings.ts @@ -94,7 +94,7 @@ type __EventObj__ = { once: ( cb: TAURI_API_EVENT.EventCallback, ) => ReturnType>; - emit: T extends null + emit: null extends T ? (payload?: T) => ReturnType : (payload: T) => ReturnType; }; diff --git a/src/lang/globals.ts b/src/lang/globals.ts index 645d343..a100a27 100644 --- a/src/lang/globals.ts +++ b/src/lang/globals.ts @@ -12,7 +12,7 @@ type __EventObj__ = { once: ( cb: TAURI_API_EVENT.EventCallback, ) => ReturnType>; - emit: T extends null + emit: null extends T ? (payload?: T) => ReturnType : (payload: T) => ReturnType; };