Reputation: 86084
Is there a type-safe way of expressing this function? In this example, I'm adding numbers, but the question is about the general pattern.
type signature =
((a: number, b: number) => number) &
((a: bigint, b: bigint) => bigint);
// Operator '+' cannot be applied to types 'number | bigint' and 'number | bigint'.
const add : signature = (a, b) => a + b;
The two arguments can be two different types, but should never be both at the same time. Is there a way to write this function type so it works?
Upvotes: 2
Views: 712
Reputation: 1543
you can define all method types and then define a method to handle all defined types.
function add(a: {option1:string}, b: number): number
function add(a: number, options: { option2: number }): number
function add(a: string, b: string, options: { options3: boolean }): number
function add(
a: string | number|{option1:string},
b: string | number | { option2: number },
c: { options3: boolean } = {options3: false}
) {
// todo
return 0;
}
add({option1:'a1'},2)
add(1,{option2:2})
add('a','b',{options3:false})
function add(a: number, b: number): number
function add(a: bigint, b: bigint): bigint
function add(a: any, b: any): number | bigint {
return a + b;
}
or use generic types
function add<T extends (string|number|bigint)>(a: T, b: T): T {
return a as any + b;
}
add('a','b');
add(1,2);
add(1,'b'); // error
Upvotes: 2