Issue with destructuring types in Typescript when assigning a response

I'm encountering an issue related to destructuring and types. In my scenario, I have defined a custom type and a function that returns that specific type:

 interface CustomNameInfo {
     name: string;
     access: string
 }

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

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

When using approach 1, everything works fine without any type errors:

 let name, access, resp;         

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

However, when attempting to use the approach involving destructuring, TypeScript throws the error: Property 'access' and namedoes not exist on typeCustomNameInfo``

 let name, access;         

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

Answer №1

Uncertain of what error you might be experiencing, but the Stackblitz example is functioning properly:

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();

By the way, refrain from using name as a top-level variable:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding information to a MySQL database using PHP/AJAX, triggering the success function only once the data has been successfully inserted (Callback)

I've been struggling to create a basic website, and some of the information provided here is confusing and irrelevant to my specific situation. My website features a form with three input fields, a button, and a list. When the submit button is clicke ...

Spawn a node process and save the result

I am currently working on a script that spawns a child process to clone a hard drive. While the script is functional, I am facing an issue when it comes to handling errors and capturing output. The problem is that only the first line of the output is sto ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...

Is it possible to inject local variables into a controller defined with ng-controller directive?

Is there a way to utilize myCtrl instead of myCtrl2 in the given example, passing an argument as a local variable rather than attached to $scope? The $controller service is capable of performing the necessary operation to encapsulate an existing controlle ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

What could be the reason for the unexpected behavior of comparing an environment variable with undefined in Jest?

During the process of creating Jest tests to validate the existence of a required environment variable, I encountered unexpected behavior while comparing the variable to undefined. The @types/node documentation implies that each environment variable is eit ...

The Google Maps API allows all markers to be connected to a single infowindow

I've been grappling with this issue for some time now, but I just can't seem to find a solution! I'm retrieving data from a database in Laravel using Ajax and then attempting to display infowindows for each marker on Google Maps. The markers ...

Issue with pointer events: pointercancel triggered by pressure-sensitive input (stylus)

Seeking your assistance in resolving an issue that I am facing while developing a web app in Chrome using React and Canvas. It appears to be related to the PointerEvent, specifically with pressure pen input. The Problem: When I attempt to draw with my tab ...

Countdown Clock for Displaying Parsing Time in C#

On my aspx page, I have a submit button that triggers the parsing of ".txt" files when clicked. The parsing process generates results stored in tables and then redirects the user to another page. However, the issue at hand is that the parsing operation t ...

Determine the data type of every element in an array containing a variety of data types

My array contains a mix of values: const array = [false, 1, '', class T {}]; The type of the array is: type arrayType = typeof array; // (string | number | boolean | typeof T) [] Each object at an index can have the following types: string | nu ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

In Vue, emitting does not trigger the parent component to update its properties

The emit is functioning properly, as I can observe in the vue developer tool. However, the property in the parent element is not updating. Child Component: <template> <div> <ul> <li v-for="(option, index) in opt ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

In order to effectively support 20-30 microservices, it is essential for me to establish a static master data system that can be

I am in possession of static data pertaining to countries, cities, and xyz. These data do not undergo frequent changes (updated once a year). Several Microservices will make use of these data, therefore I have chosen to avoid network latency by not opting ...

Error: The value for 'prepareStyles' property is undefined and cannot be read

Can anyone provide some guidance on this code snippet? I am struggling to understand the error message I am receiving. import React, {PropTypes} from 'react'; import TransactionListRow from './TransactionListRow'; import {Table, TableB ...

Having trouble getting your custom Angular directive to function properly with dynamically changing images?

Currently in the process of developing a custom directive for AngularJs that involves an image rotator based on a Jquery Plugin I created, you can check it out here Below is the code snippet for my directive: .directive('imageRotator', function ...

Steps to resolve the issue of MatCardComponent not being detected despite being imported within the module

I am encountering an issue with my Angular nrwl nx project that includes Bootstrap 5 and Angular Material. Within a library, I have a dashboard component where I import the MatCardModule. However, when trying to use it inside the DashboardComponent, I rece ...

Simple steps to access a feature on an AngularJS application

I have my angular application stored in a variable (initialized with:) var app = angular.module('app', [...]); Now, I need to access the $timeout service. How can I retrieve this service from it? I am looking for something like: var timeout ...

Issues with Javascript's JSON.parse functionalityI'm having trouble

As a complete newcomer to the world of JavaScript, I find myself struggling with some issues regarding JSON manipulation. This is my very first attempt at working with it, and I am encountering difficulties in converting my JSON string into an object that ...

Ensuring that all routes in Express 4 redirect from HTTP to HTTPS

Is there a way to redirect all http:// requests to https:// for every route in my express 4 application? I've tried this method, but it seems to cause a redirect loop error I'm currently utilizing the Express 4 Router in the following manner: ...