kristóf baján kristóf baján - 11 months ago 66
TypeScript Question

TypeScript define object structure for later use

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

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:

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

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

(code in playground)