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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With