Skip to content

fix(desktop): make BrowserWindow bindings typeable - #35907

Merged
bartlomieju merged 3 commits into
denoland:mainfrom
crowlKats:fix/desktop-binding-types
Jul 23, 2026
Merged

bartlomieju merged 3 commits into
denoland:mainfrom
crowlKats:fix/desktop-binding-types

Conversation

@crowlKats

@crowlKats crowlKats commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Closes #35837.

The bug

win.bind("stat", async (path: string) => ...) does not type check, and neither does any other typed binding. ValidBindings<T> was a mapped type that discarded T[K]:

type ValidBindings<T> = {
  [K in keyof T]: (this: BrowserWindow, ...args: BrowserWindowValue[]) => Promise<BrowserWindowReturn>;
};

So T extends ValidBindings<T> required every handler to be assignable to (...args: BrowserWindowValue[]) => .... Under strictFunctionTypes that check is contravariant in the parameters, so it demanded BrowserWindowValue (which includes null) be assignable to string. Any handler that narrows a parameter — i.e. every useful handler — was rejected.

Supplying the generic did not help; it failed the same way. In practice bind accepted nothing except a handler literally declared as ...args: BrowserWindowValue[].

Separately, BrowserWindowReturn's object arm was { readonly [key: string]: unknown }. TypeScript only grants implicit index signatures to type aliases, never to interfaces, so that arm rejected every user-declared interface, Deno.FileInfo included.

The fix

ValidBindings<T> now validates each handler and passes T[K] through unchanged, so bind keeps the caller's own parameter types and infers them from T.

BrowserWindowReturn<T> becomes a structural walk instead of a union. It accepts interfaces, including recursive and mutually-recursive ones, and rejects the values that today silently serialize to {} — Date, Map, Set, class instances with methods, and functions. any and unknown pass through, since nothing can be proven about them and rejecting them would break Record<string, unknown> payloads.

Return values are now checked even when T is left to its default, so returning a Date is a type error rather than an empty object at runtime. The check sits in parameter position rather than as an R extends BrowserWindowReturn<R> constraint, because a type parameter constrained by a conditional type over itself is circular (TS2313).

Also adds void to the serializable leaves. It was missing while undefined was present, so async () => {} — a fire-and-forget binding, the most common shape — never type checked, even though the runtime already coerces it (result ?? null).

Note for the reporter

Deno.stat() still cannot be returned directly, but now it fails with a clear error instead of a confusing one. Deno.FileInfo has Date fields, and Date does not survive the boundary. Map it to a serializable shape first:

win.bind("stat", async (path: string) => {
  const { size, isFile, mtime } = await Deno.stat(path);
  return { size, isFile, mtime: mtime?.toISOString() ?? null };
});

Follow-up, not fixed here

Date resolving to {} is a real runtime gap. BrowserWindowReturn's doc comment claims results are "serialized to JSON", but op_desktop_resolve_bind_call takes #[serde] result: serde_json::Value, so values go through serde_v8, which has no Date support — deserialize_any maps ValueType::Object to deserialize_map, and a Date has no own enumerable properties. Switching to JSON.stringify would honor toJSON() but regress Uint8Array, which currently arrives as a JSON array. Worth its own issue.

Testing

Types only; no runtime change. Verified by type checking a matrix against the real .d.ts before and after. Before: 4 errors, the first being the exact TS2345 from the issue. After: 0.

Covered as passing — no generic with narrow params; explicit generic in both method and property syntax; parameter inference from T; interface, recursive interface, discriminated union, Record<string, unknown>, Uint8Array, tuple, and void returns.

Covered as still correctly rejected, via @ts-expect-error (an unused directive is itself an error, so these are load-bearing) — wrong argument type; unknown binding name; handler return not matching the declared binding; Date, nested Date, Map, function, and method-bearing returns; Date parameter; non-async handler.

There is no type test covering lib.deno.desktop.d.ts — it is only referenced from cli/build.rs and cli/tsc/mod.rs, which is how the constraint could ship unusable. A spec test that compiles a few bind calls would be worth adding; happy to do it here or as a follow-up.

Leo Kettmeir added 2 commits July 10, 2026 13:36
`ValidBindings<T>` was a mapped type that discarded `T[K]`, replacing
every handler with a common supertype. That forced each handler's
parameters to be checked contravariantly against `BrowserWindowValue`,
so any handler narrowing a parameter — every useful handler — was
rejected. Passing an explicit type argument failed too, meaning `bind`
accepted nothing but a handler declared as `...args: BrowserWindowValue[]`.

Validate each handler and pass `T[K]` through unchanged instead, so
`bind` keeps the caller's parameter types and infers them from `T`.

`BrowserWindowReturn` was a union whose object arm was an index
signature, which rejected every user-declared `interface` — TypeScript
only grants implicit index signatures to type aliases. Replace it with a
structural walk that accepts interfaces (including recursive ones) and
rejects values that silently serialize to `{}`: `Date`, `Map`, `Set`,
class instances with methods, and functions. Returns are now checked
even when `T` is left to its default.

Also add `void` to the serializable leaves. It was absent while
`undefined` was present, so `async () => {}` never type checked, though
the runtime already coerces it via `result ?? null`.
Collapse `IsAny` + `IsUnknown` into a single `unknown extends T` guard,
which holds for exactly those two types. Fold `BrowserWindowResolved`
into the check that used it. Flatten the nested conditionals in
`ValidBindings` by comparing the parameter and return types as one
tuple. Rename `BrowserWindowReturn` to `BrowserWindowSerializable`,
since it now validates arguments as well as return values.

No behavior change: the same type-checking matrix passes and rejects.
@crowlKats
crowlKats force-pushed the fix/desktop-binding-types branch from 6d80a42 to d3971c3 Compare July 10, 2026 11:37

@bartlomieju bartlomieju left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the type logic and verified it empirically by extracting the new types standalone and running them through a deno check matrix.

Confirmed:

  • Parameter inference works under an explicit generic (name infers string, n infers number), and narrowing handlers are no longer rejected.
  • Return checking fires even with the default T: Date, Map, nested Date, and function returns all fail, with the "binding handler must resolve with a serializable value" reason surfaced through the intersection.
  • Valid shapes pass: interfaces (recursive included), discriminated unions, Record<string, unknown>, Uint8Array, and void (async () => {} now type checks, matching the runtime result ?? null).
  • ValidBindings<T> rejects a non-serializable return baked into the bindings type at the type-argument position.
  • The removed BrowserWindowReturn has no references outside the replaced lines, so the deletion is clean.

Agree the missing type test over lib.deno.desktop.d.ts is worth adding as a follow-up since that gap is how the unusable constraint shipped, but not a blocker.

LGTM.

@bartlomieju
bartlomieju merged commit 0e01f14 into denoland:main Jul 23, 2026
136 checks passed
bartlomieju added a commit that referenced this pull request Jul 23, 2026
Closes #35837

---------

Co-authored-by: Leo Kettmeir <leo@deno.com>
Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

desktop: how to properly type a binding?

2 participants