Can you explain the concept of a mapped type and its practical applications?

What is the function of this? And when would be the best scenario to utilize it?

Answer №1

Understanding Typescript Mapped Types:

When working with Typescript, there are times when we need to create types based on existing ones. Mapped types provide a concise way to generate new types that adhere to the principle of not repeating ourselves.


Dealing with Custom Properties:

  • Issue: Lack of knowledge about all properties of an object type in advance
  • Solution: Declare custom properties and type them using this syntax:

type customProperties = {
  [key: string]: string | boolean;
};

const dataObj: customProperties = {
  str: 'hello',
  boolVal: true,
  // int: 123 > Error Type 'number' is not assignable to type 'string | boolean'.
};

Benefit of Mapped Types:

  • Problem: Need to base an object type on another type without defining all properties repeatedly
  • Approach: Define custom properties using the syntax below:

type Person = {
  name: string;
  age: string;
};

// For illustration purpose only >> TypeScript has built-in Readonly, which should be used instead
type myReadonly<Type> = {
  readonly [Property in keyof Type]: Type[Property];
};

// For demonstration only >> TypeScript offers Partial, use it for partial types
type myPartial<Type> = {
  [Property in keyof Type]?: Type[Property];
};

type ReadOnlyPerson = myReadonly<Person>
type PartialPerson  = myPartial<Person>

It's worth noting that mapped types utilize the []: type syntax for custom properties. The distinction between custom properties and mapped types lies in the approach they take:

  • Mapped types iterate over properties of an existing type using generics and the [Property in keyof Type] syntax. This allows mapping all properties of the existing type to a new type that can be tailored as needed.
  • Custom properties help in typing object properties that are unknown beforehand. This is valuable when the exact structure of the object is uncertain at coding time due to potential additional properties being added later on.

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

Error: Attempting to access 'config' property of undefined variable

I am currently utilizing Vue 3 with Typescript and primevue. After integrating primevue into my application, I encountered the following errors and warnings. The issue arises when I attempt to utilize the primevue 'Menubar' component, however, wh ...

`Can you bind ngModel values to make select options searchable?`

Is there a way to connect ngModel values with select-searchable options in Ionic so that default values from localStorage are displayed? <ion-col col-6> <select-searchable okText="Select" cancelText="Cancel" cla ...

Is it possible to customize error messages in @hapi/joi?

Seeking assistance with custom error message overrides in Joi. Consider the schema outlined below. const joiSchema = Joi.object({ name: Joi.string().required(), email: Joi.string().email().required() }) try{ const schema = joiSchema.validateAsyn ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

Creating a personalized design for MUI TextField spin button

Looking to customize the appearance of the up/down spin buttons in MUI TextField. https://i.sstatic.net/DcG66.png Desiring white arrows and a black surrounding area that's slightly larger, akin to this: https://i.sstatic.net/ZxMJw.png I'm aware ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

Creating a custom Angular pipe to convert milliseconds to a formatted hh:mm:ss in Angular

Struggling to develop an Angular pipe that accurately converts milliseconds to hh:mm:ss format. Despite researching several articles, none of the solutions seem to work. Here is a snippet of the current pipe.ts implementation: transform(value) { le ...

Using functions as observer callbacks is not permitted in TypeScript

Here is a snippet of functional TypeScript code along with its test: menu.service.ts: import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; export class MenuService { private events = new Subject ...

The detection of my query parameters is not working as expected

Creating an Angular application that dynamically loads a different login page based on the "groupId" set in the URL is my current challenge. The approach involves sending each client a unique URL containing a specific "groupId" parameter. A template is the ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...

The headerStyle does not have any impact on the header component in React-Native

Currently diving into React-Native with Typescript and working on a project. Encountered a bug where the header color isn't changing as expected. Any help or insight would be greatly appreciated! -Viggo index.tsx import React, { Component } from & ...

Cross-origin error triggered by using an external API within a ReactJS application

I'm facing a common CORS issue in my application while trying to call an API. The API I am attempting to access can be found here: https://github.com/nickypangers/passport-visa-api Below is the code snippet used for making the API call: const getVi ...

Tips for passing a query parameter in a POST request using React.js

I am new to working with ReactJS and I have a question about passing boolean values in the URL as query parameters. Specifically, how can I include a boolean value like in a POST API call? The endpoint for the post call is API_SAMPLE: "/sample", Here is ...

Encountered a style group error 'non-collision' while using Angular with HERE Maps JS API 3.1

Occasionally, I encounter an error when trying to load a HERE map with the satellite base layer: Tangram [error]: Error for style group 'non-collision' for tile 13/16/15542/12554/15 Cannot read property 'retain' of undefined: TypeE ...

Filtering rows in angular based on the current data's id

currData = { id: "iStyle1", status: "PENDING" }; data = [ { id: "splitStyle1", rows: [ { id: "1cUMlNRSapc5T", row: 2, sequence: 2, status: ...

How can I identify and remove duplicate elements from an array of objects?

elements= [ { "id": 0, "name": "name1", "age": 12, "city": "cityA" }, { "id": 1, "name": "name2", "age": 7, "city": "cityC" }, { &qu ...

How can I ensure that a pop-up is shown only once per day in Vue.js

I am facing an issue with a method that is supposed to display a modal window 4 seconds after the user logs onto the website. If the modal is closed, it should not be displayed again for the next 24 hours. However, I am encountering problems with LocalSt ...