News for hackers. Stuff that matters.
Re:The visitor pattern is essentially the same thing as Chur... by lmm on Thursday February 04, 2021 @05:58AM (#26024370)
You just need to make the function generic rather than the type:

    type Shape = <T extends unknown>(
        circle: (x: number, y: number, r: number) => T,
        rectangle: (x: number, y: number, w: number, h: number) => T
    ) => T;

    function Circle<T>(x: number, y: number, r: number): Shape {
        return (_Circle, _Rectangle) => _Circle(x, y, r);
    }

    function Rectangle<T>(x: number, y: number, w: number, h: number): Shape {
        return (_Circle, _Rectangle) => _Rectangle(x, y, w, h);
    }

    const exampleCircle = Circle(2, 1.4, 4.5);
    const exampleRectangle = Rectangle(1.3, 3.1, 10.3, 7.7);

    function area(shape: Shape): number {
        return shape(
            (_x, _y, r) => Math.PI * r * r,
            (_x, _y, w, h) => w * h
        );
    }

    function main() {
        console.log(area(exampleCircle));
        console.log(area(exampleRectangle));
    }
    main()

There are no comments on this comment yet.