TypeScript define object structure for later use

kristóf baján picture kristóf baján · Aug 17, 2016 · Viewed 27.6k times · Source

Is it possible to define an object structure in TypeScript that can be used then as parameter type?

What I mean:
I have (let's say) 5 functions that return the same object structure like so:

foo(): { bar: string, baz: boolean, idk: number } { ... }
bar(): { bar: string, baz: boolean, idk: number } { ... }
...

the problem with this is that I have to define this structure at every function that returns an object like this.

So is it possible to do something like the following?

declare const OBJECT_STRUCTURE: { bar: string, baz: boolean, idk: number }

foo(): OBJECT_STRUCTURE { ... }
bar(): OBJECT_STRUCTURE { ... }
...

Answer

Nitzan Tomer picture Nitzan Tomer · Aug 17, 2016

You can use an interface:

interface MyType {
    bar: string;
    baz: boolean;
    idk: number;
}

function foo(): MyType { 
    return {
        bar: "bar",
        baz: true,
        idk: 4
    };
}

(code in playground)

Or a type alias:

type MyType = {
    bar: string;
    baz: boolean;
    idk: number;
}

function foo(): MyType { 
    return {
        bar: "bar",
        baz: true,
        idk: 4
    };
}

(code in playground)