TypeScript 定义对象结构供以后使用

TypeScript define object structure for later use

是否可以在 TypeScript 中定义一个对象结构,然后用作参数类型?

我的意思是:
我有 (比方说) 5 个函数 return 相同的对象结构,如下所示:

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

这个问题是我必须在每个 return 像这样的对象的函数中定义这个结构。

那么是否可以做类似下面的事情?

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

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

So is it possible to do something like the following

一个简单的type声明:

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

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

您可以使用 interface:

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

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

(code in playground)

或者 type alias:

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

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

(code in playground)

一个真正原生的 TS 解决方案是——声明接口

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

而且可以在任何地方轻松重用,无需重新声明

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

other(obj: IMyObject) { ... }