zmii
zmii

Reputation: 4287

Declaration of method via curly brackets in TypeScript

How to read declaration of method in this manner (or how compiler reads it):

add: {(id: number): void}

Is this like creating a type for this add method? It's strange as this reads like add is object with one function.

context:

interface ComponentProps {
  add: {(id: number): void};
}

and then when some React component implements this I will write:

<Component add={(item) => {console.log(`Added item ${item}`);} } />

Upvotes: 4

Views: 758

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250036

add is a field that is a function. The way we usually write a function signature type in typescript is (id: number) => void but this is a short form of { (id: number): void }. The two syntaxes are equivalent, both define a type that has a callable signature. This more verbose syntax has the advantage of allowing more signatures:

interface ComponentProps {
  add: {
     (id: number): void
     (id: string, otherParam: number): void
  };
}

Upvotes: 1

Related Questions