What is the best way to create a nullable object field in typescript?

Below is a function that is currently working fine:

export const optionsFunc: Function = (token: string) => {
  const options = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    }
  };

  return options;
};

I now want to enhance it by adding params to the options variable. The params should be an optional key/value pair.

How can I adjust the options variable and include the params parameter in the function?

The final result I'm aiming for is something like this:

export const optionsFunc: Function = (token: string, params: any) => {
  const options = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  if (params) {
    const filteredParams = Object.entries(params).reduce(
      (a, [k, v]) => (v == null || v === 'null' ? a : (a[k] = v, a)), {}
    );
    options.params = filteredParams;
  }

  return options;
};

Answer №1

Consider utilizing a Record to define your object:

export const optionsFunction = (token: string, parameters?: Record<string, unknown>) => {
  const settings = {
    parameters: {} as Record<string, unknown>,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  if (parameters) {
    const filteredParameters = Object.entries(parameters).reduce<Record<string, unknown>>(
      (acc, [key, value]) => (value == null || value === 'null' ? acc : (acc[key] = value, acc)), {}
    );
    settings.parameters = filteredParameters;
  }

  return settings;
};

Also, refrain from labeling optionsFunction as Function. This action disregards the types within the arrow function and the return type specified.

Subsequently, we continue using the Record to describe settings.parameters and the result type of the reduce operation.

Explore the Playground

Answer №2

One way to accomplish this is by

define interface SomeObject {
    include optionalField?: fieldType;
    ...
}

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

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Understanding NestJS Mixins and Their Distinction from Inheritance

After researching, I found that the Nestjs documentation does not include any information about mixins. Here is what I have gathered from my findings on Google and Stack Overflow: A mixin serves as a means of code sharing between classes within Nest. Esse ...

Generating an array in Javascript using JSON

I've been doing a lot of research, but I can't seem to find a solution that works for me. My goal is to retrieve the next four bus arrival times for a specific bus stop using an application that reaches out to an API returning JSON data. The issu ...

What is the indicator that signals a change in the value of a React ref.current?

Typically, when using props, we would write componentDidUpdate(oldProps) { if (oldProps.foo !== this.props.foo) { console.log('foo prop changed') } } to identify any changes in props. However, if we utilize React.createRef(), how can w ...

Adding an item to the collection

When I log my cartProducts within the forEach() loop, it successfully stores all the products. However, if I log my cartProducts outside of the loop, it displays an empty array. var cartProducts = []; const cart = await CartModel .fin ...

An inquiry regarding props in JavaScript with ReactJS

Check out the following code snippet from App.js: import React from 'react' import Member from './Member' function App () { const members = [ { name: 'Andy', age: 22 }, { name: 'Bruce', age: 33 }, { n ...

Capybara's attach_file function is not properly activating the React onChange handler in Firefox

Currently, I am conducting tests on the file upload feature of a React-built page. The page includes a hidden file input field with an onChange event listener attached to it. Upon selecting a file, the onChange event is triggered and the file is processed ...

NextJS is throwing an error: The prop `href` in `<Link>` should be a `string` or `object`, but it received `undefined` instead

I've encountered an issue while trying to integrate a header section from a GatsbyJS project into my NextJS project. The error message I'm receiving is: "Error: Failed prop type: The prop href expects a string or object in <Link>, but ...

Using Knockout to bind an element to the selected value from a dropdown list

When using the following select, I am connecting it to an observable array. <select id="selectProtocols" data-bind="options: optionsAvailable, optionsCaption:'Selecione...', optionsText: 'SimpleDescription', optionsValue:'???&a ...

Introducing an alternative solution for handling tasks linked to the completion of CSS3 animations

In order to incorporate smooth CSS3 animations into my website, I have implemented the animate.css library created by Dan Eden. One particular scenario involves a loading screen that features a fade-out animation. It is crucial for this animation to comple ...

Transform URL in AngularJS Service

An issue I'm facing with the app I'm developing is that users need to be able to change the IP address of the server where the REST API is hosted. The challenge lies in the fact that while the address is stored in a variable that can be changed, ...

Encountering issues with Jest Setup in Next.js as it appears to unexpectedly include a React import in index.test.js

Hey there, I've been pondering over this issue for the past few days. It appears to be a common error with multiple solutions. I'm facing the dreaded: Jest encountered an unexpected token /__tests__/index.test.js:16 import React from "r ...

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

Changing the height of one Div based on another Div's height

I currently have a display of four divs positioned side by side. I am seeking a solution to ensure that the height of each div remains consistent, and should adjust accordingly if one of them increases in size due to added text content. For reference, ple ...

"Implementing constraints in Postgres using Node.js

Currently, I am struggling with writing a constraint code to handle situations where a user tries to search for an id that does not exist in the database (specifically PostgreSQL). Despite my efforts, the if statement in the code below does not seem to be ...

The concept of Puppeteer involves defining the browser and page in a synchronous manner

In the beginning of the Puppeteer tutorial, it is instructed to follow this code snippet: const puppeteer = require('puppeteer'); (async () => { await page.goto('https://example.com'); const browser = await puppeteer.launch ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Pressing the submit button in the Material UI table clears all selected checkboxes

Take a look at this code snippet: https://jsfiddle.net/aewhatley/Lkuaeqdr/1/. My objective is to construct a table with a submit button utilizing Material-UI components. const { Table, TableHeader, TableHeaderColumn, TableBody, TableRow, Table ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

The VueJS app seems to be experiencing difficulties with rendering the content

Just starting out with VueJS and I have my initial files - index.html and index.js. I want to stick with just these two files and not add any more. Here's the content of index.html: <html lang="en"> <head> <meta charset ...