Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Generic Specialization

I'm looking for something akin to specialization in Typescript generics, where implementations can be disjoint based on type criteria.

A minimal example:

const someFunction = <A>() => { return 0; }

// something like this
<A extends String>someFunction = (a: A) => { return 1; }
<A extends Number>someFunction = (a: A) => { return 2; }
.
.
.

console.log(someFunction(false)); // prints 0
console.log(someFunction('string')); // prints 1
console.log(someFunction(42)); // prints 2

This is the "jist" of what I'd like. Is this possible in Typescript?

like image 340
Anthony Monterrosa Avatar asked May 14 '19 21:05

Anthony Monterrosa


People also ask

How do you define a generic type in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

Does TypeScript support generic classes?

TypeScript fully supports generics as a way to introduce type-safety into components that accept arguments and return values whose type will be indeterminate until they are consumed later in your code.

How do I create a generic object in TypeScript?

To specify generic object type in TypeScript, we can use the Record type. const myObj: Record<string, any> = { //... }; to set myObj to the Record type with string keys and any type for the property values.

How do I use generics in JavaScript?

JavaScript is a dynamically typed language and it doesn't have any generics. You can write a normal function/method, it will work for all types. P.S. Use Typescript if want to code like you do in Java.


1 Answers

What you're talking about does not exist in Typescript. The closest to this would be a function overload. Based on your example it would look something like this:

function someFunction(a: boolean): 0
function someFunction(a: string): 1
function someFunction(a: number): 2
function someFunction(a: any) {
  if(typeof a === 'boolean') {
    return 0
  } else if (typeof a === 'string') {
    return 1
  } else if (typeof a === 'number') {
    return 2
  }
}

This example works with primitives and typeof but would work the same with complex values and other type guards including User-Defined Type Guards.

like image 193
Donovan Hiland Avatar answered Nov 15 '22 13:11

Donovan Hiland