TypeScript 定义对象结构以备后用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38990762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:17:27  来源:igfitidea点击:

TypeScript define object structure for later use

typescriptdeclare

提问by kristóf baján

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

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

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

我的意思是:
我有(假设)5 个函数返回相同的对象结构,如下所示:

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

回答by Nitzan Tomer

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)

操场上的代码

回答by basarat

So is it possible to do something like the following

那么是否可以执行以下操作

A simple typedeclaration:

一个简单的type声明:

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

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

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

回答by Radim K?hler

A really native solution to TS is - declare interface

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

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