简体   繁体   中英

Typescript: destructuring type error when setting response

I am having an issue with destructuring and types. I have a custom type and a function that returns that type:

 interface CustomNameInfo {
     name: string;
     access: string
 }

 async getNameInfo(): Promise<CustomNameInfo> {
    //logic

    return {
       name: "FOO",
       access: "none"
    }
 }

if I use approach 1, I get no type errors:

 let name, access, resp;         

 if (!hasName) {
    resp = await this.getNameInfo();
    access = resp.access;
    name = resp.name;
 }

If I use the approach I am trying to use though with destructuring, I am getting the TS error: Property 'access' and name does not exist on type CustomNameInfo``

 let name, access;         

 if (!hasName) {
    ({ name, access } = await this.getNameInfo()); 
 }

Not sure, what you are doing wrong, but this Stackblitz example works as expected:

interface CustomNameInfo {
  nameVar: string;
  access: string
}

async function getNameInfo(): Promise<CustomNameInfo> {
  return {
    nameVar: "FOO",
    access: "none"
  }
}

let nameVar: any, access: any;

async function foo() {
  if (true) {
    ({ nameVar, access } = await getNameInfo());
  }
  console.log(nameVar, access )
}
foo();

BTW: don't use name as top-levle variable: https://stackoverflow.com/a/65379845/1041641

You didn't declare your variable before used-it ( var , let or const ). You must deconstruct your result like this:

const { name, access } = this.getNameInfo();

More information about deconstructing in MDN Documentation

Official mdn example:

const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;

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