TypeScript to determine the structure of the object for later use

Is it possible to define the structure of an object in TypeScript, which can then be used as a parameter type?

What I mean:
I have (say) 5 functions that return the same structure of an object, for example:

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

the problem is that I have to define this structure for every function that returns such an object.

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 { ... } ... 
+5
source share
3 answers

You can use interface :

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

( code on the playground )

Or enter an alias :

 type MyType = { bar: string; baz: boolean; idk: number; } function foo(): MyType { return { bar: "bar", baz: true, idk: 4 }; } 

( code on the playground )

+11
source

So, you can do something like the following

Simple type declaration:

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

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

+3
source

In fact, the native solution for TS is to declare an interface

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

And it could be easily reused everywhere without repeating it

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

or

 other(obj: IMyObject) { ... } 
+2
source

All Articles