Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to solve this TypeScript Generics error?

I want to make a function that receives string | undefined and also returns string | undefined. This was my first approach:

sanitizeName: (name: string | undefined): string | undefined => {
  return name?.replace(...)
},

However, when I call this function with a string argument, I know for sure it will also return a string, but now the type is string | undefined and I need an extra existence check.

What I tried is assigning a generic T that is string | undefined, and it is the parameter and returned type:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sanitizeName: <T extends string | undefined>(name: T): T => {
  return name?.replace(...)
},

In my head, this should work: if the function receives undefined, it returns undefined. If it receives a string, it returns a string.

But I got this error:

Type 'string | undefined' is not assignable to type 'T'.
  'string | undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.
    Type 'undefined' is not assignable to type 'T'.
      'undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.ts(2322)

Why is that? How can I get the desired behavior (string returns string, undefined returns undefined)?

>Solution :

I had to build a similar function, it seems like typescript cannot infer the subtype of T this way, so I had to do something like this:

function sanitizeName(name: string): string;
function sanitizeName(name: undefined): undefined;
function sanitizeName(name: string | undefined): string | undefined {
  return ...
}

Learn more here about Function Overloads

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading