TypeScript
Interfaces

Optional Properties

Not all properties are required

interface Amount {
  value: string;
  precision?: number;
}

Readonly Properties

The properties can be modified only at object creation.

interface Point {
  readonly x: number;
  readonly y: number;
}

Excess Property Checks

Object literals undergo excess property checking when

  • assigned to other variables
  • passed as arguments
interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
}

// error: 'colour' not expected in type 'SquareConfig'
let mySquare = createSquare({ colour: "red", width: 100 });

Avoid the checks

let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

Function Types

Can be used to describe functions

interface SearchFunc {
    (source: string, subString: string): boolean;
}

Indexable Types

  • Supported index signatures: string and number
  • The number will be converted to a string
  • All properties must match the return type of the index signature
interface NumberDictionary {
    [index: string]: number;
    length: number;    // ok, length is a number
    name: string;      // error, the type of 'name' is not a subtype of the indexer
}

Index signatures can be readonly

interface ReadonlyStringArray {
    readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ["Alice", "Bob"];
myArray[2] = "Mallory"; // error!

Extending Interfaces

  • An interface can extend another interface
  • Can extend multiple interfaces 
  • Interfaces can extend classes
    • inherits the members of the class but not their implementations
Made with Slides.com