Home > Net >  Typescript: destructuring type error when setting response
Typescript: destructuring type error when setting response

Time:09-02

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 namedoes not exist on typeCustomNameInfo``

 let name, access;         

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

CodePudding user response:

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

CodePudding user response:

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;
  • Related