Skip to content

Instantly share code, notes, and snippets.

@rjz
Created October 9, 2018 04:13
Show Gist options
  • Select an option

  • Save rjz/cc3adaf249e817d0d64f4785d57957eb to your computer and use it in GitHub Desktop.

Select an option

Save rjz/cc3adaf249e817d0d64f4785d57957eb to your computer and use it in GitHub Desktop.

Revisions

  1. RJ Zaworski created this gist Oct 9, 2018.
    1 change: 1 addition & 0 deletions .gitignore
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    *.js
    5 changes: 5 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    # TypeScript samples

    Build with:

    $ tsc *.ts
    22 changes: 22 additions & 0 deletions generics.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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]);

    16 changes: 16 additions & 0 deletions interface.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    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)));
    16 changes: 16 additions & 0 deletions point.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    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));