Skip to content

Instantly share code, notes, and snippets.

@rjz
Created October 9, 2018 04:13
Show Gist options
  • Save rjz/cc3adaf249e817d0d64f4785d57957eb to your computer and use it in GitHub Desktop.
Save rjz/cc3adaf249e817d0d64f4785d57957eb to your computer and use it in GitHub Desktop.

TypeScript samples

Build with:

  $ tsc *.ts
interface Bounds {
readonly w: number,
readonly h: number,
area(): number,
}
type Circle = Bounds & {
readonly r: number,
}
function circle (r: number) {
const area = () => Math.PI * r * r;
return { r, h: r + r, w: r + r, area };
}
const mapper = <T, U>(f: (t: T) => U) =>
(ts: T[]) => ts.map(f);
const circleMapper = mapper<number, Circle>(circle);
const circles = circleMapper([1, 2, 3]);
interface Bounds {
readonly w: number, // width
readonly h: number, // height
area(): number,
}
function square (w: number, h: number) {
const area = () => w * h;
return { h, w, area };
}
function perimeter (b: Bounds) {
return 2 * (b.w + b.h);
}
console.log(perimeter(square(2, 4)));
type Point = {
x: number,
y: number,
};
const add =
(p1: Point, p2: Point): Point => ({
x: p1.x + p2.x,
y: p1.y + p2.y,
});
const p: Point = { x: 1, y: 1 };
const o: Point = { x: 2, y: 3 };
console.log(add(p, o));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment