What is the process for destructuring an interface in TypeScript?

My request is as follows:

const listCompartmentsRequest: identity.requests.ListCompartmentsRequest = {
  compartmentId: id,
  compartmentIdInSubtree: true,
}

I want to shorten the long line

identity.requests.ListCompartmentsRequest
.

I'm looking for something like this:

const { ListCompartmentsRequest } = identity.requests

const listCompartmentsRequest: ListCompartmentsRequest = {
  compartmentId: id,
  compartmentIdInSubtree: true,
}

Even though I have tried it, I'm encountering this error:

ListCompartmentsRequest refers to a value, but is being used as a type here. Did you mean typeof ListCompartmentsRequest?"

Answer №1

According to the MDN documentation about Destructuring assignment:

The syntax of destructuring assignment in JavaScript allows for unpacking values from arrays or extracting properties from objects into separate variables.

Destructuring applies only to values, not types — TypeScript currently lacks a similar syntax. Alternatively, you can define a new type alias that represents the nested member of the type you described. Here is an example:

TS Playground

type Identity = {
  Requests: {
    ListCompartmentsRequest: {
      compartmentId: string;
      compartmentIdInSubtree: boolean;
    };
  };
};

type ListCompartmentsRequest = Identity['Requests']['ListCompartmentsRequest'];

const id = '123';

const listCompartmentsRequest: ListCompartmentsRequest = {
  compartmentId: id,
  compartmentIdInSubtree: true,
};

If your target type is within a namespace, you can use dot notation to access the nested type.

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

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Tips for showing that every field in a typed form group must be filled out

Starting from Angular 14, reactive forms are now strictly typed by default (Typed Forms). This new feature is quite convenient. I recently created a basic login form as shown below. form = this.fb.group({ username: ['', [Validators.required ...

Tips for integrating Reactjs with Chessboard.js

Recently, I stumbled upon chessboardjs (https://chessboardjs.com/) as a way to hone my React coding skills. However, I hit a roadblock while trying to implement a simple example of displaying the chess board in my application. The documentation instructed ...

What method can be used to specify a function of any signature that returns a particular type in programming?

I am looking to define a unique type that must be a function which, when executed, will always produce an object containing the property type: string. The input parameters for this function are of no concern. For instance: foo(1, 'bar'); // res ...

Setting up VSCode to run various tasks

My TypeScript project in Visual Studio Code has a specific task outlined as follows: { "version": "0.1.0", // The command is tsc. "command": "tsc", // Show the output window only if unrecognized errors occur. "showOutput": "silent", // Und ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

The specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...

Obtaining the current row index in React MUI Data Grid using React-Context

Scenario In my application, I have implemented an MUI Data Grid with custom components in each row: RowSlider, RowDate, and RowLock using the MUI Components Slider, Date Picker, and Button respectively. View the Data Grid Visualization The Slider and Da ...

Adding markers to a map in Angular 2 using ngOnInit after initialization

Embarking on my Angular journey by creating a sample app incorporating GoogleMaps. import { Component, Input, OnInit, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FormControl } from '@ ...

Using Typescript inject with Vue 3 is currently not functioning as expected. The issue arises when trying to create spread types from object types

When using Vue 3 and TypeScript, an error is encountered (as shown below) only when the script lang="ts" attribute is present. Can someone provide insight into why the inject function in Vue 3 with TypeScript does not function correctly? ERROR in src/compo ...

What is the best way to send my Array containing Objects to the reducer using dispatch in redux?

I'm currently facing an issue where I can only pass one array item at a time through my dispatch, but I need to pass the entire array of objects. Despite having everything set up with a single array item and being able to map and display the data in t ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

Is it possible to configure TypeScript (or a tool similar to ESLint) to throw an error when a library returns undefined?

Currently working with knex and sometimes it returns any, for example when forgetting to specify the table type in the query. Are there any recommended tools available to avoid this issue, ensuring all knex queries are typed properly? ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...

Tips for efficiently passing TypeScript constants to Vue templates without triggering excessive reactivity

I'm curious about the most efficient way to pass a constant value to a template. Currently, I am using the data property in Vue, but I believe that is better suited for state that changes over time as Vue adds event listeners to data properties. The c ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

TS2559: Type 'String' lacks any common properties with type 'object'

When working with TypeScript, I encountered an issue with a map defined as shown below that is intended to accept (key, value) pairs of (string, anything). let map = new Map<String, Object>() Upon attempting to insert a (key, value) pair into the ma ...

Discovering the file system with window.resolveLocalFileSystemURL in Typescript for Ionic 3

After reviewing the documentation found on this link for the File plugin, I came across a paragraph that discusses how to add data to a log file. See the example code below: window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) ...

Creating a Typescript interface that includes keys from another interface

interface A{ a: string; b: string; c: string; // potentially more properties } interface B{ [K in keyof A]: Boolean; } What could be the issue with this code? My goal is to generate a similar structure programmatically: interface B{ ...

Referring to a component type causes a cycle of dependencies

I have a unique situation where I am using a single service to open multiple dialogs, some of which can trigger other dialogs through the same service. The dynamic dialog service from PrimeNg is being used to open a dialog component by Type<any>. Ho ...