Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 { ... }
...
like image 627
kristóf baján Avatar asked Aug 17 '16 07:08

kristóf baján


People also ask

How do you define a struct in TypeScript?

TypeScript is a Structural Type System. A structural type system means that when comparing types, TypeScript only takes into account the members on the type. This is in contrast to nominal type systems, where you could create two types but could not assign them to each other.

Is it bad practice to use any in TypeScript?

any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.

How do I create a nested object in TypeScript?

Use an interface or a type alias to type a nested object in TypeScript. You can set properties on the interface that point to nested objects. The type of the object can have as deeply nested properties as necessary.


1 Answers

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)

like image 142
Nitzan Tomer Avatar answered Dec 24 '22 00:12

Nitzan Tomer