Typescript interfaces

From wikinotes
Revision as of 00:30, 17 December 2022 by Will (talk | contribs) (Will moved page Typescript interface to Typescript interfaces without leaving a redirect)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In typescript, interfaces are implicit -- any object that satisfies the requested interface is allowed.
Interfaces can be extended (grown) into new interfaces that include others.

Interface

interface Person {
    name: string;
}

interface Employee extends Person {
    id: number;
}

function getId(employee: Employee): number {
    return employee.id;
}

getId({ id: 1, name: "vaderd" });                   // valid (has both 'id', 'name')
getId({ id: 2, name: "palpatine", isRoot: true });  // valid (extra param ignored, interface matched)
getId({ name: "lukes" })                            // invalid (missing id)

Type Alias

You can also define a type-alias, but you cannot extend it in a new interface.

type Point {
    x: number;
    y: number;
}