What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>(
  data: T,
  normalize?: (data: T) => NT,
) {
  const normalizedData = normalize ? normalize(data) : {};

  return Object.keys(normalizedData);
}

customFunction(10, (v) => v);
// Error(Type 'number' is not assignable to type 'Record<string, string | number | boolean>')
// This behavior is CORRECT

customFunction(10, (data) => ({ data }));
// No error
// This behavior is CORRECT

customFunction({ data: 10 }, (v) => v);
// No error
// This behavior is CORRECT

function adjustedFunction<T, NT extends Record<string, string | number | boolean>>(
  data: T,
  normalize: (data: T) => NT = (v) => v, 
   // ERROR: Type 'T' is not assignable to type 'NT'.
   // 'NT' could be instantiated with an arbitrary type which could be unrelated to 'T'
) {
  const normalizedData = normalize(data);

  return Object.keys(normalizedData);
}

adjustedFunction(10); 
// no error
// This behavior is INCORRECT, should throw an error

adjustedFunction(10, (data) => ({ data }));
// WORKS
// This behavior is CORRECT

adjustedFunction({ data: 10 });
// WORKS
// This behavior is CORRECT

The function customFunction has been adapted to meet the requirement of having the normalize parameter optional with a default value. The default value for normalize is set to an empty object if it is not provided.

To rewrite adjustedFunction to fit the requirements, conditional typing and default values can be used appropriately to handle different scenarios and ensure correct behavior.

Answer №1

After receiving input from @spender, I managed to come up with a solution.

type ChooseType<A, B> = A extends B ? A : never;

function customFunction<S extends Record<string, string | number | boolean>>(
  inputData: S,
): string[];
function customFunction<S, NS extends Record<string, string | number | boolean>>(
  inputData: S,
  transform: (inputData: S) => NS,
): string[];
function customFunction<S, NS extends Record<string, string | number | boolean>>(
  inputData: S, 
  transform: (inputData: S) => NS = (val) => val as ChooseType<S, NS>
) {
  const transformedData = transform(inputData);

  return Object.keys(transformedData);
}

Despite implementing my ChooseType, I still feel there is room for improvement. Any suggestions are welcome.

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

Angular: ChangeDetection not being triggered for asynchronous processes specifically in versions greater than or equal to Chrome 64

Currently, I'm utilizing the ResizeObserver in Angular to monitor the size of an element. observer = new window.ResizeObserver(entries => { ... someComponent.width = width; }); observer.observe(target); Check out this working example ...

What is the best way to choose checkboxes from data that is passed dynamically?

https://i.stack.imgur.com/L3k59.png I am looking to add an edit feature to my application. When the user clicks on the edit option, they should be taken to a different page with the previously entered value displayed. While I have successfully retrieved ...

Exploring ways to display all filtered chips in Angular

As a new developer working on an existing codebase, my current task involves displaying all the chips inside a card when a specific chip is selected from the Chip List. However, I'm struggling to modify the code to achieve this functionality. Any help ...

Retrieve an array of information and convert it into an object using Angular

My previous data is displaying correctly in the chart, as shown below: @Component({ selector: 'app-inpout-bar-chart', templateUrl: './inpout-bar-chart.component.html', styleUrls: ['./inpout-bar-chart.component.scss'] }) exp ...

Tips for choosing an HTML element using Playwright with TypeScript

My goal is to use playwright with typescript in order to select a specific html element. The element I am trying to target has the class "ivu-select-dropdown" and a specific style. <div class="ivu-select-dropdown" style="position: absolut ...

Include a log out option in the side menu of the ionic2 application

I am working with the sidemenu template to kick off my application. I aim to incorporate a button within the sidemenu that enables users to trigger a modal alert for confirming logout. Below is the code snippet: app.component.ts: import { Component, View ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

What is the best way to show all cards in Angular when no filtering input is provided?

I have implemented a filter feature for multiple cards in Angular using Pipes. The filter works well, but I am facing an issue where no cards are displayed when there is no input value provided. I would like all the cards to be displayed when no input is g ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Error encountered: Uncaught SyntaxError - An unexpected token '<' was found while matching all routes within the Next.js middleware

I am implementing a code in the middleware.ts file to redirect users to specific pages based on their role. Here is the code snippet: import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { get ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

Encountering a 403 error when attempting to upload files to Google Cloud Storage (GCS) using Signed URLs

The main aim is to create a signed URL in the api/fileupload.js file for uploading the file to GCS. Then, retrieve the signed URL from the Nextjs server through the nextjs API at localhost://3000/api/fileupload. Finally, use the generated signed URL to upl ...

No updates found (Angular)

When a button is clicked, a test method is triggered with i as the index of an element in an array. The test method then changes the value of the URL (located inside the sMediaData object) to null or '' and sends the entire sMediaData to the pare ...

Error message: Duplicate identifier found in Typescript

Encountering an error while trying to run my angular-meteor client (ionic serve), specifically: [00:29:20] typescript: node_modules/meteor-typings/1.3/main.d.ts, line: 657 Duplicate identifier 'Status'. L657: type Status ...

Expanding the properties of an object dynamically and 'directly' by utilizing `this` in JavaScript/TypeScript

Is it possible to directly add properties from an object "directly" to this of a class in JavaScript/TypeScript, bypassing the need to loop through the object properties and create them manually? I have attempted something like this but it doesn't se ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...