Skip to content

Instantly share code, notes, and snippets.

@bennidi
Created February 24, 2022 08:35
Show Gist options
  • Save bennidi/cd457c2c10169f232b2bbf42c79e9235 to your computer and use it in GitHub Desktop.
Save bennidi/cd457c2c10169f232b2bbf42c79e9235 to your computer and use it in GitHub Desktop.
Typescript Demystified

Functions can have properties, that's what the object literal syntax is for: it allows to define a call signature and additional properties. Your two examples are equivalent because the second doesn't define additional properties on the object literal. You can read more on that in the section on hybrid types.

Additionally, the object literal allows to define multiple call signatures for function overloads. You can create an object of such an interface with Object.assign:`

interface Foo {
    (x: string): number,
    (x: number): string,
    bar: Array<any>,
}

const foo: Foo = Object.assign(function (x: any) {
    if (typeof x === 'string') {
        return parseInt(x);
    } else {
        return x.toString();
    }
}, {
    bar: []
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment