-1

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()); 
 }
sal3jfc
  • 517
  • 4
  • 14

1 Answers1

1

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

TmTron
  • 17,012
  • 10
  • 94
  • 142