TypeScript define object structure for later use

荒凉一梦 提交于 2020-08-02 06:06:40

问题


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 { ... }
...

回答1:


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)




回答2:


So is it possible to do something like the following

A simple type declaration:

type OBJECT_STRUCTURE = { bar: string, baz: boolean, idk: number }

More : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html




回答3:


A really native solution to TS is - declare interface

export interface IMyObject { 
    bar: string;
    baz: boolean; 
    idk: number;
}

And that could be easily reused everywhere, without re-declaring it

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

or

other(obj: IMyObject) { ... }


来源:https://stackoverflow.com/questions/38990762/typescript-define-object-structure-for-later-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!