简体   繁体   中英

Redeclare destructured variables in Typescript

I want to use destructuring in Typescript GraphQL. A lot of the API functions use data as the first level key. How can I do the below without a Typescript/TSLint error. Changing to var will result in it wanting to be let , which Cannot redeclare block-scoped variable & block-scoped used before its declaration . const of course is an error. Removing the 2nd let will not allow me to destructure the 2nd data .

let {data}:OverlayEventDetail = await modal.onDidDismiss();
if (data.save) {
  if (shop) {
    //update
  } else {
    const input: CreateShopInput = {
      name: typeof data.name === 'string' && data.name.length > 0 ? data.name : null,
      keywords: []
    };
    let {data}:{data:CreateBlahMutation} = await API.graphql(graphqlOperation(mutations.createShop, {input}));
  }
}

My current solution is with both const {data} and // @ts-ignore on the name line.

You can do the assignment without declaring the variable. You will need to add parentheses around the statement though:

({data} = await API.graphql(graphqlOperation(mutations.createShop, {input})));

Although you can't reuse the name, you can still destructure while assigning to a different variable:

let {data: apiData}: {data:CreateBlahMutation} = await API.graphql(graphqlOperation(mutations.createShop, {input}));

This will assign the data property of await API.graphql(...) to the variable apiData .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM