Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active May 3, 2022 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/ec510a28803483f6a07f200c44b93d6e to your computer and use it in GitHub Desktop.
Save mizchi/ec510a28803483f6a07f200c44b93d6e to your computer and use it in GitHub Desktop.
export type Point = {
t: 'point',
readonly x: number;
readonly y: number;
}
function get_distance(this: Point, other: Point) {
return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
}
type Display<T> = {
display(t: T): string;
}
function display<T>(this: T, impl: Display<T>) {
return impl.display(this);
}
// usage
const display_for_point: Display<Point> = {
display(self: Point) {
return `(${self.x}, ${self.y})`;
}
}
const p1: Point = { t: 'point', x: 0, y: 0 } as const;
const p2: Point = { t: 'point', x: 3, y: 4 } as const;
const ret = get_distance.call(p1, p2);
console.log(ret);
console.log(display.call(p2, display_for_point));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment