Maintain the default type for the generic type parameter

I am attempting to work around a few optional generic type parameters and keep them as defaults that have already been set.

Here is a sample code snippet:

interface Foo<T, T1 = string, T2 = boolean> {
    ID: T
    Name: T1
    IsActive: T2
}

There are 3 type parameters to consider:

  • T -- this is mandatory
  • T1 -- optional, default value is string
  • T2 -- optional, default value is boolean

I aim to generate data with the specifications below:

  • T -- number
  • T1 -- <DEFAULT which is string>
  • T2 -- number
const data:Foo<number, ..., number> = {
    ID: 1,
    Name: "apache", // the name type should be a string
    IsActive: 1,
}

Answer №1

At the moment, there is no specific syntax available to "skip" a generic type argument for default values or inference by the compiler. There has been a long-standing feature request open for this at microsoft/TypeScript#26242. If this feature ever gets implemented, you might be able to use something like Foo<number, , number>, Foo<number, *, number>, or Foo<number, infer, number>.

Until that happens, the workaround is to explicitly define the types as in Foo<number, string, number>, or find alternative solutions.


If your intention of "skipping" is to obtain the default value, one workaround is to create a custom type to represent "skip," then adjust your type accordingly. For example:

interface $ { ___SIGIL___: true; } // $ denotes "skip"
type Default<T, U> = [T] extends [$] ? U : T;

Instead of type F<T = X, U = Y, V = Z>, you would now write

type MyF<T = $, U = $, V = $> = F<Default<T, X>, Default<U, Y>, Default<V, Z>>
. For a type like Foo, it could look like:

type FooT1Default = Foo<any> extends Foo<any, infer T1, any> ? T1 : never;
// type FooT1Default = string

type FooT2Default = Foo<any> extends Foo<any, any, infer T2> ? T2 : never;
// type FooT2Default = boolean

type MyFoo<T, T1=$, T2=$> = 
  Foo<T, Default<T1, FooT1Default>, Default<T2, FooT2Default>>;

You can test it with:

type Example = MyFoo
// type Example = Foo<number, string, number>

const data: MyFoo = {
    ID: 1,
    Name: "apache", // okay
    IsActive: 1,
}

Visit the Playground link for this code snippet

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

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

Make sure that every component in create-react-app includes an import for react so that it can be properly

Currently, I am working on a TypeScript project based on create-react-app which serves as the foundation for a React component that I plan to release as a standalone package. However, when using this package externally, I need to ensure that import React ...

Navigating with Angular 2: Redirecting Azure AD login URI

I am currently exploring Azure AD integration for logging into an Angular 2 application. The Github link provided below demonstrates a simple method to log in without the use of any authentication libraries. Sign in via Microsoft Graph using Typescript an ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Generate an interactive sitemap.xml in ReactJS for each request made to http://example.com/sitemap.xml

I am working on a single-page application (SPA) using reactjs, and I have links in the format of http://example.com/blog/:id. I want to dynamically generate a sitemap for this site. While I'm aware that there are npm packages like react-router-sitema ...

How to prevent redundant object declarations when passing parameters in TypeScript?

Motivation for Using Object Parameters One of the motivations behind using objects as function parameters is to allow the caller to clearly define arguments with specified field names, which can make code reviews easier. Challenge When Using Implements an ...

Is it possible to implement a feature in Angular and Bootstrap where the toggle menu can be closed by clicking anywhere on the page, rather than just the toggle button

I'm working on an Angular project where I've implemented a navbar component. The navbar is responsive and includes a toggle button that appears when the browser window is resized. This button allows users to hide or display the menus. One issue ...

Exploring the Relationship Between the ngOnInit and ionViewWillLoad Lifecycle Hooks

After a few months of utilizing Ionic Framework (ionic-angular 3.9.2 latest) for developing Progressive Web Apps, I find myself pondering the distinction between ngOnInit and ionViewWillLoad. If my understanding serves me right, ngOnInit is an Angular lif ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

What is the best way to save data from a Firebaselistobservable into an array?

I've been attempting to transfer data from Firebase to an array using Angular 2, but I'm facing difficulties in pushing the data into the array. Below is the code snippet: Variables: uid: string = ''; agencyItems: FirebaseListObserva ...

Ways to turn off specific ngtsc warnings

Ever since updating my Angular app to version 15, I've been noticing some warnings popping up in both the terminal and Chrome DevTools. Is there a way to turn off or disable these warnings? I keep seeing this warning message about the optional chain o ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project. ASP.NET Framework Web API 4.7 Angular CLI: 13.3.7 Angular: 13.3.11 On the Web API end: Controller: [EnableCors(origins: "*", headers: "*", ...

The Vue $refs Object is classified as 'unidentified' in nature

I'm encountering an issue while attempting to utilize $refs in my Vue 3 application. Each time I try, I receive the Typescript error stating that "Object is of type 'unknown'". I am uncertain about how to resolve this problem. Here's ...

Exploring LocalStorage Monitoring in Vue.js 2

How can I stay informed about any changes in Banana.vue? I have tried using addEventListener, @watch but it doesn't seem to be working... The index.vue file is importing both Apple.vue and Banana.vue In Apple.vue: localStorage.setItem('fruit ...

Unique TypeScript code snippets tailored for VSCode

Is it possible to create detailed custom user snippets in VS Code for TypeScript functions such as: someArray.forEach((val: getTypeFromArrayOnTheFly){ } I was able to create a simple snippet, but I am unsure how to make it appear after typing an array na ...

Testing server sent events with Angular solely using Karma-Jasmine

I am currently developing a web application using Angular for the frontend and Python for the backend. My implementation involves utilizing server-sent events (SSE) to stream data from the server to the user interface. While everything is functioning prope ...