These examples are ordered in approximately increasing order of complexity.

Documentation

Code

Declaration

Use declare namespace to describe types or values accessed by dotted notation.

  1. declare namespace myLib {
    function makeGreeting(s: string): string;
    let numberOfGreetings: number;
    }

Overloaded Functions

Documentation

The getWidget function accepts a number and returns a Widget, or accepts a string and returns a Widget array.

Code

  1. let x: Widget = getWidget(43);
    let arr: Widget[] = getWidget("all of them");

Declaration

  1. declare function getWidget(n: number): Widget;
    declare function getWidget(s: string): Widget[];

Documentation

When specifying a greeting, you must pass a GreetingSettings object. This object has the following properties:

1 - greeting: Mandatory string

2 - duration: Optional length of time (in milliseconds)

Code

  1. greet({
    greeting: "hello world",
    duration: 4000
    });

Declaration

Use an interface to define a type with properties.

Reusable Types (Type Aliases)

Documentation

Code

  1. function getGreeting() {
    return "howdy";
    }
    class MyGreeter extends Greeter {}
    greet("hello");
    greet(getGreeting);
    greet(new MyGreeter());

Declaration

You can use a type alias to make a shorthand for a type:

  1. type GreetingLike = string | (() => string) | MyGreeter;
    declare function greet(g: GreetingLike): void;

Documentation

The greeter object can log to a file or display an alert. You can provide LogOptions to .log(...) and alert options to .alert(...)

Code

    Declaration

    Use namespaces to organize types.

    1. declare namespace GreetingLib {
      interface LogOptions {
      verbose?: boolean;
      }
      interface AlertOptions {
      modal: boolean;
      title?: string;
      color?: string;
      }
      }

    You can also create nested namespaces in one declaration:

    Classes

    Code

    Declaration

    Use declare class to describe a class or class-like object. Classes can have properties and methods as well as a constructor.

    1. declare class Greeter {
      constructor(greeting: string);
      greeting: string;
      showGreeting(): void;
      }

    Documentation

    The global variable foo contains the number of widgets present.

    Code

    1. console.log("Half the number of widgets is " + foo / 2);

    Declaration

    Use declare var to declare variables. If the variable is read-only, you can use declare const. You can also use declare let if the variable is block-scoped.

    1. /** The number of widgets present */
      declare var foo: number;

    Global Functions

    Documentation

    Code

    Declaration

    Use declare function to declare functions.