Let’s start from the bottom line: there’s a simple alternative to typing Typescript functions, that’s more concise and logical than the Typescript’s “native” method. It makes use of a utility type, which I’ll call simply Function, that is easily defined:
type Function<A = any[], B = any> = (...args: A extends any[] ? A : [A]) => B;
view raw
Function.ts hosted with ❤ by GitHub
For example:
function minimumOf(fn: Function<number, number>, interval: [number, number]) {
// Approximate/solve...
}
// Works!
const m1 = minimumOf(Math.sqrt, [1, 3]);
// Argument of type '(x: number, y: number) => number' is not assignable to parameter of type 'Functiona<[number], number>'.
const m2 = minimumOf(Math.pow, [1, 3]);
view raw
Function-exmaples.ts hosted with ❤ by GitHub
Feel free to save it, and use it wherever you find it valuable!
There’s no hack behind this definition — it simply uses some of Typescript’s advanced features effectively:
fn
parameter in the example above, A and B both become number types.[number, boolean]
, the compiler will interpret that as a function that receives two parameters — the first is a number, and the second is a boolean.#function