It looks like I am not getting any kind of compile time exhaustive checking for the…
- User
It looks like I am not getting any kind of compile time exhaustive checking for the match code
Assistant
The current implementation does not provide compile-time exhaustive checking for the
matchcode.The reason is that TypeScript's type system is not powerful enough to infer that all cases are handled exhaustively in the
matchmethod.However, we can add a feature to ensure that all cases are handled exhaustively at compile-time.
One way to achieve this is by using a technique called "discriminated unions" along with a helper type to check if all cases are handled.
Here's an updated version of your code:
ts// A generic function to assert that a value is of type 'never'. function assertNever(value: never): never { throw new Error(`Unhandled ADT case: ${JSON.stringify(value)}`); } // Helper type to extract constructor names from union U type ConstructorNames<U> = U extends { constructor: { name: infer N } } ? N : never; // The core ADT class with a generic match method. abstract class ADT { public match<U extends ADT, TReturn>( this: U, handlers: { [K in ConstructorNames<U>]: (value: Extract<U, { constructor: { name: K } }>) => TReturn; } & { [key: string]: never } // Add this to ensure all cases are handled ): TReturn { const handler = (handlers as any)[this.constructor.name]; if (handler) { return handler(this as any); } return assertNever(this as never); } } // ----------------------------------------------------------------------------- // Example 1: The Color ADT // ----------------------------------------------------------------------------- class Red extends ADT { constructor() { super(); } } class Green extends ADT { constructor() { super(); } } class Blue extends ADT { constructor() { super(); } } type Color = Red | Green | Blue; const myColor: Color = new Blue(); const hexCode = myColor.match<Color, string>({ Red: (value) => '#FF0000', Green: (value) => '#00FF00', Blue: (value) => '#0000FF', }); console.log(`Exhaustive Match Hex Code: ${hexCode}`); // ----------------------------------------------------------------------------- // Example 2: The Shape ADT // ----------------------------------------------------------------------------- class Circle extends ADT { constructor(public radius: number) { super(); } } class Square extends ADT { constructor(public side: number) { super(); } } type Shape = Circle | Square; const myShape: Shape = new Square(10); const area = myShape.match<Shape, number>({ Circle: (value) => Math.PI * value.radius ** 2, Square: (value) => value.side ** 2, }); console.log(`Exhaustive Match Area: ${area}`); // Test exhaustive checking // @ts-expect-error const incompleteMatch = myColor.match<Color, string>({ Red: (value) => '#FF0000', Green: (value) => '#00FF00', });
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.