Maintain the specific type based on the provided data, rather than the default value, when a related generic is defined

When it comes to unit tests, I prefer a more flexible approach with dynamic generic types that eliminate the need for type casting.

I want T to be open-ended, but if I specify a type, I expect to receive an exact match.

For R, I need it to precisely match the type of params, regardless of whether T is specified or not.

The issue arises when specifying T and being required to also define R. I have attempted setting its default value to { [key: string]: any }, however, this disrupts the types and fails to accurately reflect the params type.

declare function test<T, R extends { [key: string]: any } = { [key: string]: any }>(
  template: string,
  params: R,
): {t: T, r: R};

// testing without specific generics
const test1 = test('f', {
  a: 'a',
});

test1.t; // expectedly unknown as no specific type was provided
test1.r.a; // expected behavior - recognized as a string
test1.r.b; // expected failure since property does not exist

// testing with a specified generic
const test2 = test<string>('f', {
  a: 'a',
});

test2.t; // expectedly a string
test2.r.a; // failed - treats it as any instead of a string
test2.r.b; // failed - treats it as any instead of forbidding it 

// Attempting another solution
declare function anotherTest<T>(
  template: string,
  params: { [key: string]: any },
): {t: T, r: typeof params}; // aiming for the passed type, not default { [key: string]: any }

It seems challenging to achieve this without separating params into an independent variable and defining its type explicitly. If you have a solution, please share. Thank you in advance!

TS Playground

Answer №1

Unfortunately, the feature is not currently available but the good news is that it is currently in development:

https://github.com/microsoft/TypeScript/issues/10571 https://github.com/microsoft/TypeScript/pull/26349

A potential solution will involve using infer as the key mechanism.

type TypeConstraint = string | boolean;
function getName<A, infer B extends TypeConstraint>(a: A, b: B): B {}

// valid
const abc: boolean = getName<string>("abc", true);
const abc: boolean = getName<string, boolean>("abc", true);

// error
const abc: boolean = getName<string>("abc", 10);

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

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

Creating a structured state declaration in NGXS for optimal organization

Currently, I'm delving into the world of NGXS alongside the Emitters plugin within Angular, and I find myself struggling to grasp how to organize my state files effectively. So far, I've managed to define a basic .state file in the following man ...

Using a comma as a decimal separator for input is not permitted when working with angular/typescript/html

I am facing an issue with my Angular frontend where I have numerous html input fields that trigger calculations upon typing. <input type="text" [(ngModel)]="myModel.myAttribute" (input)="calculate()"> The problem arise ...

Steps for activating the HTML select option menu with an external button click

I'm currently in the process of building a React website and I'm faced with the challenge of customizing select options to align with my design in Figma. Check out this image for reference Here's how I've set it up in my code: const C ...

Troubleshooting import errors with Typescript for C3 and D3 libraries

I have recently started working on a project using the C3 graphing library within an Ionic2/Angular2 TypeScript setup. After installing C3 via npm and the type definitions via tsd, I imported it into my own TypeScript file like this: import {Component} fr ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

Determining the type inference in Typescript based on column data objects

Within my object that describes my table, I have a property called dataFields, which is an array of data with 3 keys - name (a required string), label (a required string), and field (an optional string). Now, I would like to add another property called tes ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Imitate dependencies using Mocha and Typescript

In my typescript project, I am using mocha. Let's consider two modules: // http.ts export class Http { } // app.ts import Http from './http'; export class App { } I want to know how to mock the Http module while testing the App. The te ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

Error message stating 'Module not found' is displaying in the browser console

As a beginner with Angular CLI, I recently executed the following commands at the root of my Angular project. issue-management\src\webui>ng generate module pages\dashboard issue-management\src\webui>ng generate component pag ...

What is the proper way to incorporate ts-nameof in the gulp build process and encounter the error message: 'getCustomTransformers' is a compiler option that is not recognized

Utilizing ts-nameof in my TypeScript files, similar to this example in a .ts file: import 'ts-nameof'; export class MyTsNameOfTest { public testTsNameOf() { const nameString = nameof(console.log); } } My Gulp build task setup - followi ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

"Exploring the process of extracting data from a JSON URL using NextJS, TypeScript, and presenting the

After tirelessly searching for a solution, I found myself unable to reach a concrete conclusion. I was able to import { useRouter } from next/router and successfully parse a local JSON file, but my goal is to parse a JSON object from a URL. One example of ...

Execute a grandchild function in Angular that triggers its grandparent function

I'm currently working with a component structure that looks like this: Component A -> Component B -> Component C Within the template of Component C, there is a button that triggers a function in the 'code behind' when clicked. My goal is ...

Having trouble importing components from the module generated by Angular CLI library

After creating a simple Angular library using CLI with the command ng g library <library-name>, I encountered an issue while trying to import a component from its module. In my app module, I added components.module to the imports array and attempted ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...