How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type:

type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = {
  record: R,
  array: A
}

There is a function that directly uses the MyCustomType:

const customFunction = <R extends Record<string, string> | undefined, A extends string[] | undefined>(myData: MyCustomType<R, A>)=>{
  // ... //
}

The requirement is to be able to omit the record prop if it's not defined in the generic type. Here's an example:

const recordInfo = getTheRecord() // Assuming getTheRecord() returns undefined here
const sampleArray = ['a']
customFunction<undefined, string[]>({
  array: sampleArray
})

Is there a way to make certain props optional in relation to a generic type?

Answer №1

Avoid the need to include undefined within the extend clause in order to accomplish your desired outcome. To allow for a scenario of "either Record or undefined", without explicitly assigning undefined, consider implementing this using a partial type:

type NewType<X extends Record<string, string>, Y extends string[]> = {
  record?: X
  array?: Y
}

const newFunction = <X extends Record<string, string>, Y extends string[]>(newObject: NewType<X, Y>)=>{
  // ... //
}

Answer №2

Stumbled upon this solution:

This method appears to be effective!

type ConvertUndefinedToOptional<T> = { [Key in keyof T]-?:
  (x: undefined extends T[Key] ? { [Prop in Key]?: T[Key] } : { [Prop in Key]: T[Key] }) => void
}[keyof T] extends (x: infer Input) => void ?
  Input extends infer Output ? { [Key in keyof Output]: Output[Key] } : never : never

type CustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = {
  record: R
  array: A
}

const customFunction = <R extends Record<string, string> | undefined, A extends string[] | undefined>(object: ConvertUndefinedToOptional<CustomType<R, A>>)=>{
  // ... //
}

const newArray = ['b']
customFunction<undefined, string[]>({
  array: newArray
})

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

unable to utilize a tip with d3 version 5 in a TypeScript environment?

i'm facing an issue with the following code snippet: var tip = d3.tip() .attr('class', 'd3-tip') .attr('id', 'tooltip') .html(function(d) { return d; }) .direction('n ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading wh ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

The parent class has not been specified

I am facing an issue with my parent class, HTTPConnection, which I intend to use as a network utility class in order to avoid redundant code. However, when attempting to utilize it, the file core.umd.js throws an error stating Uncaught ReferenceError: HTTP ...

Solve the error "Property 'container' of null is not accessible" in musickit.js while running an Angular application on a server

I am currently developing an application that combines Angular and MusicKit to offer users the ability to listen to music simultaneously. However, I encountered a challenging error when trying to run the application using ng serve --host x.x.x.x instead of ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Having difficulty retrieving the file from Google Drive through googleapis

I'm currently attempting to retrieve a file from Google Drive using the Googleapis V3, but I keep encountering an error message stating: 'Property 'on' does not exist on type 'GaxiosPromise<Schema$File>'. Below is the c ...

Unable to simulate a static method in Vitest - encountering an error stating "is not a function"

I am currently writing unit tests using the Vitest framework for my TypeScript and React application, but I have encountered an issue with mocking static methods. Below is a snippet of my code: export class Person { private age: number; constructor(p ...

What is the proper way to specify the type for the `clean-element` higher-order-component in React?

Error message: 'typeof TextareaAutosize' argument cannot be assigned to a type 'Component<{}, {}, any>'. Error: Property 'setState' is not found in 'typeof TextareaAutosize'. Here is the code snippet causin ...

What is the best way to add JSX to the DOM using React?

Looking to make an addition to my DOM. let parent = document.getElementById("TabContainer"); let settings = <Box id="test"> <GlobalSettings activeTab={"test"}></GlobalSettings> </Box> ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Set up variables during instantiation or within the class declaration

Is there a preferred way to initialize class variables in ReactJS with TypeScript - in the constructor or when declaring the variable? Both methods seem to work equally well and result in the same transpiled javascript. export class MyClass extends Reac ...

Disruptions in typing occur due to errors popping up while utilizing zod and react-hook-forms within a TypeScript application

Currently, I am working on developing a registration page for users using react-hook-forms for the registration form and zod for validation. Initially, when testing the form, I noticed that errors only appeared after submitting the form. However, once the ...

Component remains populated even after values have been reset

My child component is structured as shown below, ChildComponent.html <div> <button type="button" data-toggle="dropdown" aria-haspopup="true" (click)="toggleDropdown()"> {{ selectedItemName }} <span></span> </but ...

What is the procedure for a parent component to transmit HTML to a child component within Angular?

How can a parent component pass multiple ng-templates to a child component? For example, the parent component includes multiple ng-templates: <app-childcomponent> <ng-template>Item A</ng-template> <ng-template>Item B</n ...

efficiently managing errors in a Nest Jest microservice with RabbitMQ

https://i.sstatic.net/sUGm1.png There seems to be an issue with this microservice, If I throw an exception in the users Service, it should be returned back to the gateway and then to the client However, this is not happening! The client only sees the de ...