2 ms·
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,
by lmm 6y ago
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()