What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used.

The issue I'm facing is that although there are no TypeScript errors in the code snippet below, when I call the function like testingInterfacesFunction(), I encounter the following error:

Cannot read properties of undefined (reading 'title')

interface Success {
  onSuccess: (x: any) => void | null
  successTitle: string
  successSubtitle: string
  successIcon: "success" | "info" | "error" | "question" | "warning"
}
interface Denial {
  onDenied: (x: any) => void | null
  denialTitle: string
  denialSubtitle: string
  denyIcon: "success" | "info" | "error" | "question" | "warning"
}
interface Dismiss {
  onDismissed: (x: any) => void
  dismissTitle: string
  dismissSubtitle: string
  dismissIcon: "success" | "info" | "error" | "question" | "warning"
}
interface Extra {
  confirmButton: string
  cancelButton: string
  focus: boolean
}
interface Params {
  title: string
  subTitle: string
  icon: "success" | "info" | "error" | "question" | "warning"
  success: Success
  deny: Denial
  dismiss: Dismiss
  extra: Extra
}

const testingInterfacesFunction = (params: Params) => {
  const {
    title = "",
    subTitle = "",
    icon = "question",
    success: { onSuccess = null, successTitle = "", successSubtitle = "", successIcon = "success" },
    deny: { onDenied = null, denialTitle = "", denialSubtitle = "", denyIcon = "error" },
    dismiss: { onDismissed = null, dismissTitle = "", dismissSubtitle = "", dismissIcon = "error" },
    extra: { confirmButton = "done", cancelButton = "cancel", focus = false }
  } = params

... the body of the function ...

}

I even tried to use console.log for the title, but it seems like the function's body is not being executed at all...

All I want is to create a function that can optionally accept these properties and uses defaults if not provided. How can I achieve this?

Answer №1

For those looking to set a default value, the key is to perform the destruction within the function's arguments.

An alternative method is using "defaults" in destructuring:

(function test({a = "foo", b = "bar"} = {}) {
  console.log(a + " " + b);
})();

This technique isn't limited to function parameters; 
it can be utilized in any destructuring expression.

Answer №2

Here is an example:

    const customizeInterface = (options: {
        title = "",
        subtitle = "",
        icon = "question",
        success: { onSuccess = null, successTitle = "", successSubtitle = "", successIcon = "success" },
        deny: { onDenied = null, denialTitle = "", denialSubtitle = "", denyIcon = "error" },
        dismiss: { onDismissed = null, dismissTitle = "", dismissSubtitle = "", dismissIcon = "error" },
        extra: { confirmButton = "done", cancelButton = "cancel", focus = false }
      }) => Options {
    
    ... body of the function ...
    
    }

customizeInterface( {title: "aCustomTitle", icon:"customIcon"} )

To set default values for specific elements within success or dismiss, additional code for de-structuring is needed.

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

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

Building an expansive navigation menu with react-bootstrap

My current project involves creating a mega menu. Although I successfully made a responsive navbar, the challenge now is to implement a dropdown panel with 100% width. I've tried various approaches but haven't found one that works. Note: The oth ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

typegrapql encounters an issue with experimentalDecorators

I'm currently delving into TypeGraphQL and working on building a basic resolver. My code snippet is as follows: @Resolver() class HelloReslover { @Query(() => String) async hello(){ return "hello wtold" } } However, ...

Adjust the dimensions of an element using Protractor

When using the getSize method, I am able to determine the size of an element but I am struggling to understand how to change its height. To provide some additional context, my goal is to verify if a user can resize a textarea element. Should I simply adju ...

Transform an array of string values that occur multiple times into an array of objects organized by their index

Assuming I have a list structured as follows: [ "id1", "01-01-2019", "name1", "€ 5,60", "id2", "02-01-2019", "name2", "€ 5,70", "id3", "03-01-2019", "name3", "€ 5,20", ... ] and my goal is to transform it into a list of JSON objects ...

Receiving an error in Typescript when passing an object dynamically to a React component

Encountering a typescript error while attempting to pass dynamic values to a React component: Error message: Property 'title' does not exist on type 'string'.ts(2339) import { useTranslation } from "react-i18next"; import ...

NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an ...

Retrieve the value of a property in a JavaScript object by specifying a dynamic key for the property

As I work on my current project, I find myself immersed in a world of SVG animations. The challenge lies in triggering these animations as the user scrolls down to view the SVGs. To address this, I took the approach of creating functions for each Snap.SVG ...

Utilize jQuery to dynamically apply Bootstrap classes while scrolling through a webpage

Having an issue with jQuery. Trying to include the fixed-top class (Bootstrap 4) when scrolling, but it's not working as expected. jQuery(document).ready(function($){ var scroll = $(window).scrollTop(); if (scroll >= 500) { $(".robig").a ...

Exploring a POST request using jQuery

Apologies if I struggle with my question or use incorrect terminology, as I am new to this. I have a basic web service that processes a JSON string and returns a JSON result. Here is the code: $jsonStr = ''; if(isset($_POST['request'] ...

Typescript service wrapper class returning Axios HEAD request

I am attempting to retrieve the header response using a custom Axios HTTP service wrapper. axiosClass.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; class Http { private instance: AxiosInstance | null = n ...

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

Display the output returned from the AJAX request (HTML and/or JavaScript)

How can I effectively render content from an ajax call when the response may include html and/or javascript? I used to rely on document.write() for synchronous calls, but now that I need to use asynchronous calls, I have to find a different approach to dis ...

Turning off devtools in Next.js

Currently, my focus is on developing an application using Next.js and I am in search of a way to prevent the opening of devtools. While exploring npm packages, I came across a promising tool called Disable-devtool - npm link. However, Next.js keeps present ...

Personalize Drop-Down Selection

Currently implementing bootstrap on a site and seeking to enhance the dropdown menu customization. The default navbar appearance is present, with dropdown elements appearing upon hover. My goal is to include an icon next to each item in the navbar and ha ...

Ways to display or conceal dual views within a single Marionette js region

In my LayoutView, I have set up two regions: the filter region and the main region (Content Region). The main region displays a view based on the selection made in the filter region. Currently, I have a view for the main region called Current Year view. H ...

When attempting to add a new row to a table, the function fails to function properly

I am facing an issue with my dynamic HTML table. Each row in the table should have two cells whose values are multiplied together. I have created a function to achieve this, but it only works on the first row of the table and not on any new rows added by c ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...