Reputation: 12669
Say I have the functions
add(x : number, y : number)
subtract(x : number, y : number)
Is it possible to do something like
type common = x : number, y : number
add<common>()
So I don't need to redefine the exact same things multiple times?
Upvotes: 0
Views: 67
Reputation: 748
Carlo's answer comes close, but I would use spread arguments and a named tuple:
type X_Y = [x: number, y: number];
function add(...args: X_Y) { return args[0] + args[1] };
function subtract(...args: X_Y) { return args[0] - args[1] };
add(1, 2);
subtract(1, 2);
If the result type is also always the same, you can consider creating one type for the whole operation:
type Op = (x: number, y: number) => number;
const add: Op = (x, y) => x + y
const substract: Op = (x, y) => x - y
add(1, 2)
subtract(1, 2)
Upvotes: 1
Reputation: 392
a maybe not so elegant but:
type x_y = [number,number];
function add(i:x_y){
return i[0]+i[1];
}
Upvotes: 0