✨ Narrow the fallback to unhandled keys

The fallback is now the second factory argument — `(handlers, (s) => …)` —
so its parameter is `Exclude<T, keyof handlers>`. A property's contextual
type is fixed before TypeScript infers its sibling keys, so the remainder is
not expressible while the fallback sits in the handler map; a later argument
is contextually typed from inference on an earlier one.

Both factories take the new shape; the tests and autocomplete probes follow.
The generic overloads guard excess keys with type-fest's `Exact`, so the
error lands on the offending property. A redundant fallback (a full handler
map plus one) is still accepted — the guard for it does not survive inference
and is left to its backlog task.
This commit is contained in:
tmu committed 2026-09-18 23:08:16 +00:00
1 parent cc88c07961
commit 2d3577716d
2 files changed
+101 -128

No files matched your search

+58 -97
View File
@@ -99,22 +99,24 @@ test("getMatcher: dispatches on mixed string and numeric keys", () => {
// API: getMatcher — ❌ Exhaustive (fallback) / ✔️ ReturnsStrict // API: getMatcher — ❌ Exhaustive (fallback) / ✔️ ReturnsStrict
// ============================================================================ // ============================================================================
test("getMatcher: a `_` fallback makes the universe keys optional", () => { test("getMatcher: a `_` fallback receives the unhandled keys", () => {
// Arrange // Arrange
const factory = getMatcher<"a" | "b" | "c">(); const factory = getMatcher<"a" | "b" | "c">();
// Act // Act
const matcher = factory({ const matcher = factory(
{
a: (s): 1 | 2 => { a: (s): 1 | 2 => {
expectTypeOf(s).toEqualTypeOf<"a">(); expectTypeOf(s).toEqualTypeOf<"a">();
return 1; return 1;
}, },
_: (s): 1 | 2 => { },
// The fallback sees the whole union, not a single literal. (s): 1 | 2 => {
expectTypeOf(s).toEqualTypeOf<"a" | "b" | "c">(); // The fallback sees only the keys `a` did not handle.
expectTypeOf(s).toEqualTypeOf<"b" | "c">();
return 2; return 2;
}, },
}); );
// Assert // Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | "c") => 1 | 2>(); expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | "c") => 1 | 2>();
@@ -125,34 +127,13 @@ test("getMatcher: a `_` fallback makes the universe keys optional", () => {
assert.equal(matcher("c"), 2); assert.equal(matcher("c"), 2);
}); });
test("getMatcher: a `_` fallback also accepts an exhaustive pattern", () => {
// Arrange
const factory = getMatcher<"a" | "b">();
// Act
const matcher = factory({
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
return "A";
},
b: (s) => {
expectTypeOf(s).toEqualTypeOf<"b">();
return "B";
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b") => string>();
assert.equal(matcher("a"), "A");
assert.equal(matcher("b"), "B");
});
test("getMatcher: a `_` fallback routes mixed string and numeric gaps", () => { test("getMatcher: a `_` fallback routes mixed string and numeric gaps", () => {
// Arrange // Arrange
const factory = getMatcher<"a" | "b" | 1 | 2>(); const factory = getMatcher<"a" | "b" | 1 | 2>();
// Act // Act
const matcher = factory({ const matcher = factory(
{
a: (s): string => { a: (s): string => {
expectTypeOf(s).toEqualTypeOf<"a">(); expectTypeOf(s).toEqualTypeOf<"a">();
return "A"; return "A";
@@ -161,11 +142,12 @@ test("getMatcher: a `_` fallback routes mixed string and numeric gaps", () => {
expectTypeOf(n).toEqualTypeOf<1>(); expectTypeOf(n).toEqualTypeOf<1>();
return "one"; return "one";
}, },
_: (s): string => { },
expectTypeOf(s).toEqualTypeOf<"a" | "b" | 1 | 2>(); (s): string => {
expectTypeOf(s).toEqualTypeOf<"b" | 2>();
return "fallback"; return "fallback";
}, },
}); );
// Assert // Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | 1 | 2) => string>(); expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | 1 | 2) => string>();
@@ -247,17 +229,19 @@ test("getMatcherW: a `_` fallback widens gaps into the union", () => {
const factory = getMatcherW<"x" | "y" | "z">(); const factory = getMatcherW<"x" | "y" | "z">();
// Act // Act
const matcher = factory({ const matcher = factory(
{
x: (s) => { x: (s) => {
expectTypeOf(s).toEqualTypeOf<"x">(); expectTypeOf(s).toEqualTypeOf<"x">();
return 1 as const; return 1 as const;
}, },
_: (s) => { },
// The fallback sees the whole union, not a single literal. (s) => {
expectTypeOf(s).toEqualTypeOf<"x" | "y" | "z">(); // The fallback sees only the keys `x` did not handle.
expectTypeOf(s).toEqualTypeOf<"y" | "z">();
return "fallback" as const; return "fallback" as const;
}, },
}); );
// Assert // Assert
expectTypeOf(matcher).toEqualTypeOf< expectTypeOf(matcher).toEqualTypeOf<
@@ -275,7 +259,8 @@ test("getMatcherW: a `_` fallback widens mixed string and numeric returns", () =
const factory = getMatcherW<"a" | "b" | 1 | 2>(); const factory = getMatcherW<"a" | "b" | 1 | 2>();
// Act // Act
const matcher = factory({ const matcher = factory(
{
a: (s) => { a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">(); expectTypeOf(s).toEqualTypeOf<"a">();
return "A" as const; return "A" as const;
@@ -284,11 +269,12 @@ test("getMatcherW: a `_` fallback widens mixed string and numeric returns", () =
expectTypeOf(n).toEqualTypeOf<1>(); expectTypeOf(n).toEqualTypeOf<1>();
return 10 as const; return 10 as const;
}, },
_: (s) => { },
expectTypeOf(s).toEqualTypeOf<"a" | "b" | 1 | 2>(); (s) => {
expectTypeOf(s).toEqualTypeOf<"b" | 2>();
return "fallback" as const; return "fallback" as const;
}, },
}); );
// Assert // Assert
// ❌ ReturnsStrict: mixed handler returns widen to their union. // ❌ ReturnsStrict: mixed handler returns widen to their union.
@@ -301,28 +287,6 @@ test("getMatcherW: a `_` fallback widens mixed string and numeric returns", () =
assert.equal(matcher(2), "fallback"); assert.equal(matcher(2), "fallback");
}); });
test("getMatcherW: a `_` fallback also accepts an exhaustive pattern", () => {
// Arrange
const factory = getMatcherW<"x" | "y">();
// Act
const matcher = factory({
x: (s) => {
expectTypeOf(s).toEqualTypeOf<"x">();
return 1 as const;
},
y: (s) => {
expectTypeOf(s).toEqualTypeOf<"y">();
return "two" as const;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "x" | "y") => 1 | "two">();
assert.equal(matcher("x"), 1);
assert.equal(matcher("y"), "two");
});
// ============================================================================ // ============================================================================
// Factory contracts — calls that must not compile // Factory contracts — calls that must not compile
// ============================================================================ // ============================================================================
@@ -341,7 +305,7 @@ test("getMatcher factory rejects patterns outside its contract", () => {
// @ts-expect-error `c` is not part of the universe `"a" | "b"` // @ts-expect-error `c` is not part of the universe `"a" | "b"`
c: () => 3, c: () => 3,
}); });
// @ts-expect-error a gap without `_` is not exhaustive // @ts-expect-error a gap without a `_` fallback is not exhaustive
factory({ a: () => 1 }); factory({ a: () => 1 });
}); });
@@ -350,13 +314,13 @@ test("getMatcherW factory rejects patterns outside its contract", () => {
const factory = getMatcherW<"x" | "y">(); const factory = getMatcherW<"x" | "y">();
// Act / Assert — the calls below must not compile // Act / Assert — the calls below must not compile
// @ts-expect-error `z` is not part of the universe `"x" | "y"`
factory({ factory({
x: () => 1 as const, x: () => 1 as const,
y: () => 2 as const, y: () => 2 as const,
// @ts-expect-error `z` is not part of the universe `"x" | "y"`
z: () => 3 as const, z: () => 3 as const,
}); });
// @ts-expect-error a gap without `_` is not exhaustive // @ts-expect-error a gap without a `_` fallback is not exhaustive
factory({ x: () => 1 as const }); factory({ x: () => 1 as const });
}); });
@@ -374,11 +338,17 @@ const UNIVERSE = `"a" | "b" | "c"`;
// One session per probe: the tests share no language-server state (open // One session per probe: the tests share no language-server state (open
// documents, project membership), so they pass in any order. // documents, project membership), so they pass in any order.
const labelsFor = ( interface LabelsProbe {
name: string, readonly name: string;
factory: "getMatcher" | "getMatcherW", readonly factory: "getMatcher" | "getMatcherW";
body: string, readonly body: string;
): Promise<readonly string[]> => { }
const labelsFor = ({
name,
factory,
body,
}: LabelsProbe): Promise<readonly string[]> => {
const session = new LspSession(REPO_ROOT); const session = new LspSession(REPO_ROOT);
const target: CompletionTarget = { const target: CompletionTarget = {
file: `src/__autocomplete_${name}.ts`, file: `src/__autocomplete_${name}.ts`,
@@ -396,16 +366,20 @@ const labelsFor = (
.finally(() => session.close()); .finally(() => session.close());
}; };
test("autocomplete: an exhaustive pattern requires the universe, `_` optional", () => { test("autocomplete: an exhaustive pattern requires the universe", () => {
// Arrange // Arrange
const name = "getMatcher_fresh"; const name = "getMatcher_fresh";
// Act // Act
const labels = labelsFor(name, "getMatcher", " /*COMPLETE*/"); const labels = labelsFor({
name,
factory: "getMatcher",
body: " /*COMPLETE*/",
});
// Assert // Assert
return labels.then((result) => { return labels.then((result) => {
assert.deepEqual([...result], ["_?", "a", "b", "c"]); assert.deepEqual([...result], ["a", "b", "c"]);
}); });
}); });
@@ -414,32 +388,15 @@ test("autocomplete: handled keys drop out of the popup", () => {
const name = "getMatcher_after_key"; const name = "getMatcher_after_key";
// Act // Act
const labels = labelsFor( const labels = labelsFor({
name, name,
"getMatcher", factory: "getMatcher",
" a: () => 1,\n /*COMPLETE*/", body: " a: () => 1,\n /*COMPLETE*/",
);
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["_?", "b", "c"]);
}); });
});
test("autocomplete: `_` makes the remaining keys optional", () => {
// Arrange
const name = "getMatcher_after_fallback";
// Act
const labels = labelsFor(
name,
"getMatcher",
" _: () => 0,\n /*COMPLETE*/",
);
// Assert // Assert
return labels.then((result) => { return labels.then((result) => {
assert.deepEqual([...result], ["a?", "b?", "c?"]); assert.deepEqual([...result], ["b", "c"]);
}); });
}); });
@@ -448,10 +405,14 @@ test("autocomplete: `getMatcherW` offers the same popup as `getMatcher`", () =>
const name = "getMatcherW_fresh"; const name = "getMatcherW_fresh";
// Act // Act
const labels = labelsFor(name, "getMatcherW", " /*COMPLETE*/"); const labels = labelsFor({
name,
factory: "getMatcherW",
body: " /*COMPLETE*/",
});
// Assert // Assert
return labels.then((result) => { return labels.then((result) => {
assert.deepEqual([...result], ["_?", "a", "b", "c"]); assert.deepEqual([...result], ["a", "b", "c"]);
}); });
}); });
+43 -31
View File
@@ -1,4 +1,4 @@
import type { ValueOf } from "type-fest"; import type { Exact, ValueOf } from "type-fest";
type UnaryFn<T, R> = (shape: T) => R; type UnaryFn<T, R> = (shape: T) => R;
@@ -8,54 +8,66 @@ type PatternReturns<P> = ReturnType<
Extract<ValueOf<P>, (...args: never[]) => unknown> Extract<ValueOf<P>, (...args: never[]) => unknown>
>; >;
type Handlers<R, T extends string | number> = { [K in T]: UnaryFn<K, R> }; type Handlers<T extends string | number, R> = { [K in T]: UnaryFn<K, R> };
// Fallback form: `_` is a required key, the T-keys are optional. // The fallback is a *second argument*, not a property of the handler map,
type Fallback<R, T extends string | number> = Partial<Handlers<R, T>> & { // because its parameter is the remainder `Exclude<T, keyof Handled>` and TypeScript
_: UnaryFn<T, R>; // fixes a property's contextual type before it infers its sibling keys. A later
}; // argument, by contrast, is contextually typed from inference on an earlier
// one, so the split is what makes the remainder expressible at all.
// See development/library.md.
type Fallback<T extends string | number, Handled, R> = UnaryFn<
Exclude<T, keyof Handled>,
R
>;
// Completion form: T-keys required, `_` optional. Overload #1, because // TypeScript does not apply the excess-property check to a generic constraint,
// TypeScript takes the *first* overload as the contextual type for the popup. // so `Exact` restores it for the generic forms: a handler map can otherwise
type ExhaustiveLoose<R, T extends string | number> = Handlers<R, T> & { // carry keys outside `T`.
_?: UnaryFn<T, R>;
};
// oxlint-disable typescript/unified-signatures // oxlint-disable typescript/unified-signatures
// Strict returns: one common `R`. Overload order is load-bearing: // Strict returns: one common `R`. Overload order is load-bearing:
// #1 ExhaustiveLoose -> autocomplete `_?, a, b` // #1 Handlers (first) -> the exhaustive form and the autocomplete popup
// #2 Fallback -> accepts a partial pattern // #2 Fallback (last) -> accepts a partial handler map plus a fallback
// #3 Handlers (last) -> "Property 'b' is missing" is the reported error
interface MatcherStrict<T extends string | number> { interface MatcherStrict<T extends string | number> {
<R>(pattern: ExhaustiveLoose<R, T>): UnaryFn<T, R>; <R>(handlers: Handlers<T, R>): UnaryFn<T, R>;
<R>(pattern: Fallback<R, T>): UnaryFn<T, R>; <R, Handled extends Exact<Partial<Handlers<T, R>>, Handled>>(
<R>(pattern: Handlers<R, T>): UnaryFn<T, R>; handlers: Handled,
fallback: Fallback<T, Handled, R>,
): UnaryFn<T, R>;
} }
// oxlint-enable typescript/unified-signatures // oxlint-enable typescript/unified-signatures
// Widened returns: the union of every handler's return type. `P` is inferred // Widened returns: the union of every handler's return type. `P` is inferred
// from the whole parameter, whose closed constraint supplies the // from the whole handler map, whose closed constraint supplies the
// contextual/autocomplete type; the `keyof P` guard appended to each overload // contextual/autocomplete type.
// rejects keys outside `T`/`_`. // oxlint-disable typescript/unified-signatures
interface MatcherWidening<T extends string | number> { interface MatcherWidening<T extends string | number> {
<P extends ExhaustiveLoose<unknown, T>>( <P extends Exact<Handlers<T, unknown>, P>>(
pattern: P & (keyof P extends T | "_" ? unknown : never), handlers: P,
): UnaryFn<T, PatternReturns<P>>;
<P extends Fallback<unknown, T>>(
pattern: P & (keyof P extends T | "_" ? unknown : never),
): UnaryFn<T, PatternReturns<P>>;
<P extends Handlers<unknown, T>>(
pattern: P & (keyof P extends T | "_" ? unknown : never),
): UnaryFn<T, PatternReturns<P>>; ): UnaryFn<T, PatternReturns<P>>;
<R, Handled extends Exact<Partial<Handlers<T, unknown>>, Handled>>(
handlers: Handled,
fallback: Fallback<T, Handled, R>,
): UnaryFn<T, PatternReturns<Handled> | R>;
} }
// oxlint-enable typescript/unified-signatures
type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>; type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>;
const dispatch = const dispatch =
(pattern: HandlerMap) => (handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
(shape: string | number): unknown => (shape: string | number): unknown =>
// oxlint-disable-next-line typescript/no-non-null-assertion typescript/no-unsafe-type-assertion (
(pattern[shape] ?? pattern["_"]!)(shape as never); handlers[shape] ??
fallback ??
(() => {
throw new Error(`Unhandled shape: ${shape}`);
})
)(
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
shape as never,
);
export const getMatcher = <T extends string | number>(): MatcherStrict<T> => export const getMatcher = <T extends string | number>(): MatcherStrict<T> =>
dispatch; dispatch;