Jordan
Jordan

Reputation: 4823

Destructuring assignment with rename and typing information

How do I destructure a variable into a new name while keeping typing information?

renderItem({item:'apple'})

// jsx:
function renderItem({item: region}) {
    // region == 'apple'
    return <div>{region}</div>;
}

The above will destructure an object with item and assign it to region.

How do I express typing information for this function signature?

Upvotes: 5

Views: 4628

Answers (2)

Joe Warner
Joe Warner

Reputation: 3452

Information about the typing of the feature is available in the TypeScript 2.1 documentation:

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

Object rests are the dual of object spreads, in that they can extract any extra properties that don’t get picked up when destructuring an element:

When the Rest portion of the feature is used, it enhances object destructuring by enabling us to collect the rest of the properties into a new object comprised of them.

We can write the type annotation as we would for any other value. This is prefered as it can stop your function signatures getting verbose For example

interface IRenderItem {
  item: String
}

function renderItem({ item: region }: IRenderItem): void {
  console.log(item);
}

Upvotes: 5

Jordan
Jordan

Reputation: 4823

Type the incoming item like so:

function renderItem({item: region}:{item:string}){}

Upvotes: 10

Related Questions