Develop a utility function that maintains the data types provided in Typescript

Here is a scenario I am working on:

I need to develop a function that maintains the correct data types.

Input

type A = {a: number|undefined, string: b} | string
type B = {a: number|null, string: b} | string

type FnType = (a: {a: number | null, string: b}) => {a: number | undefined, b: string}
type FnType2 = (a: {a: number | undefined, string: b}) => {a: number | null, b: string}
type FnType3 = (a: {c: string | undefined, string: d: number}) => {a: string | null, d: number}

Function implementation

const example = (fn) => (value) => {
   if(typeof value === 'string') return value
   return fn(value)
}

The result type of the example function can correspond to either type A or type B depending on whether it's using FnType or FnType2. The key point here is that we are only certain that the value could be a string, and the fn function itself can vary.

To comprehend this feature better, one can analyze the example function and ensure that the types are inferred correctly.

For instance, when passing a function with the signature

(a: {a: string | undefined}): => { a: string | null }
, the signature of the value would then be

string | {a: string | undefined}

and the returned type from the example function would be interpreted as

{a: string | null} | string

If manually defining this process for mapping from A to B, one would follow these steps and repeat in reverse to map back from null to undefined:

const mapper = (val: { a: { key1: number | undefined } | string }): { a: { key1: number | null } | string }} => {
   return {
      a: typeof val.a === 'string' ? val.a : 
          {
              key1: val.a.key1 ?? null
          }
      }

}

Answer №1

Looks like we've found the solution...

function customFunction<A, B>(func: (input: A) => B) {
  return (inputValue: string | A) => {
    if (typeof inputValue === 'string') return inputValue;
    return func(inputValue);
  };
}

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 versatile sorting algorithm

Currently, I am working on converting the material UI sorting feature into a generic type. This will enable me to utilize it across various tables. However, I have hit a roadblock in implementing the stableSort function, which relies on the getSorting func ...

The Ins and Outs of Selecting the Correct Module to Attach a Controller in NestJS CLI

My experience with NestJS has been great so far, especially the Module system and how easy it is to parse requests. However, I have a question about the NestJS CLI. Let's say I have multiple modules. When I create a controller using the command "nes ...

Setting up the TSLint plugin for SonarQube within Jenkins

After installing the TSLint plugin for Sonarqube on my Jenkins server using https://github.com/Pablissimo/SonarTsPlugin, I found that the git page does not provide clear instructions on how to set the configuration properties and values. Specifically, I ...

Determine to which observable in the list the error corresponds

const obs1$ = this.service.getAllItems(); const obs2$ = this.service.getItemById(1); combineLatest([obs1$, obs2$]) .subscribe(pair => { const items = pair[0]; const item = pair[1]; // perform actions }, err => { // det ...

What is the best method for retrieving GET parameters in an Angular2 application?

Is there a way in Angular2 to retrieve GET parameters and store them locally similar to how sessions are handled in PHP? GET Params URL I need to obtain the access_token before navigating to the Dashboard component, which makes secure REST Webservice cal ...

Understanding Angular's Scoping Challenges

I have a function that retrieves an array and assigns it to this.usStates. main(){ this.addressService.getState().subscribe( (data:any)=>{ this.usStates = data; if(this.usStates.length===0) { this.notificationServic ...

Using logical operators with potential undefined values in TypeScript

I've encountered an error that I'm struggling to fully understand. It seems to be related to the fact that a certain value might be undefined, requiring me to check if it exists. However, when setting up the code as shown below, errors occur. Sur ...

Is it possible for TypeScript to deduce the type of a discriminated union using "extracted" boolean logic?

Recently, I've been using discriminated unions (DU) more frequently and have really started to appreciate their benefits. However, I've encountered a challenge that I can't seem to resolve. When I include a boolean check inline for the DU, T ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

Understanding TypeScript - Changing immutability and reversing Readonly<T>

Let's consider a scenario where I have the following mutable class: class Foo { constructor(public bar: any) { } } I am able to create instances of this class with readonly properties like this: const foo: Readonly<Foo> = new Foo(123); fo ...

Is there a way to validate an input field and display error messages using a TypeScript file instead of directly in the HTML file within Angular 4?

I am just starting out with Angular, so please bear with me if my question seems basic. I'm eager to learn and hopeful that I can find the answers I need here. Currently, I have implemented validation for an input field that captures a user's Fi ...

Error TS2532 in TypeScript indicates that there is a possibility that the object is undefined

Yesterday, WebStorm 2020.1 was installed on my computer. All of a sudden, I started encountering numerous TS2532 errors. https://i.sstatic.net/QXg4M.png How is it even possible for this to be "undefined"? Doesn't selectedOwner && prevent th ...

Using Angular's Hostbinding feature to toggle a button and change the background color of the

How can I change the background color of a page and all child components when a toggle button is clicked? Can this be accomplished using HostBinding in Angular? <div class="mainbody" [class.bgnight]="haveClass"> <button (click) ...

What is the best way to find the average within different groups in a JavaScript Array?

I am currently working with the Angular JS framework and have a NodeJS array like this: var arr = [{"object":"Anguille","fct":"Type A","value":"2"},{"object":"Athérine"," ...

"Mastering Data Transmission in Angular 2: A Guide to Sending Data via HTTP Services

My challenge involves processing an array of URLs by sending them to an HTTP service as part of the URL path and then generating results based on the response type. The example array I have is: this.urlArray = ["www.test.com","www.test2.com"]; Basically, ...

Issue TS2345: Cannot use type 'Product | undefined' as an argument for type 'Product[] | PromiseLike<Product[]>'

Having trouble retrieving my products using their IDs You can find the code here ...

Ensuring Koa ctx.query is valid prior to invoking the handler function

I'm currently working on a basic route that looks like this: router.get('/twitter/tweets', async (ctx) => { const { limit, page, search } = ctx.query ctx.body = { tweets: await twitter.all(limit, page, search), } }) The issue I ...

Ways to retrieve various elements produced by the ngFor directive in Angular

Is there a way to dynamically add CSS classes to div elements generated with *ngFor Angular directive? I initially attempted using @ViewChild directive and Renderer2, but encountered issues when working with multiple elements. Then, I explored manipulating ...

Can one generate an enum based on a specific type?

I have a preference: preference Preference = 'OptionA' | 'OptionB' Is it feasible to generate an enumeration from this preference? For instance: enumeration Enum = { OptionA, OptionB } I am uncertain about the feasibility of this. ...

What is the best way to organize the snapshots folder in a React project?

Currently, I am working on a React UI project that I must build by myself. Given the small size of the project, I have decided to use TypeScript and adopt a Test-Driven Development (TDD) approach. During this process, I've familiarized myself with be ...