by runarberg · 6y ago · 0 comments
It is a bit hard to define complex types. E.g. I couldn’t for the life of me annotate the return value of the pipe function:
function pipe(init, ...ops) {
return ops.reduce((acc, op) => op(acc), init)
}
For these instances they suggest writing a declaration file[2]. However I have found the documentation isn’t really clear on this usecase (in fact I find the documentation of TypeScript somewhat lacking in general).But overall getting these typehints into my editor environment has been worth it. And I haven’t had to sacrifice the save → run workflow.
1: https://www.typescriptlang.org/docs/handbook/type-checking-j...
2: https://www.typescriptlang.org/docs/handbook/declaration-fil...
EDIT: An example annotated JS file for typescript: https://github.com/runarberg/strawberry-router/blob/master/s...
`npm run check` just runs typescript’s type checker, there is no compile step.
Don't feel bad, no one can do that (yet! I think it should be possible with Variadic Tuple Types, coming in TS 4). There are a couple of attempts[1][2], but they all lack in some way. Redux does it with a boatload of overloads [3].
1: https://dev.to/ascorbic/creating-a-typed-compose-function-in...
2: https://stackoverflow.com/a/53066700/1586229
3: https://github.com/reduxjs/redux/blob/686d29b5d4e2dcb6709c16...
function pipe<T>(init: T, ...ops: ((x: T) => T)[]): T{
let r:T = ops.reduce((acc:T, op) => op(acc), init);
return r;
}
I had 5 years experience fixing type errors in C++; typescript seems like a dream in comparison.Edit: I just realized your operations probably DON'T return the same type that they are passed; they probably work in a chain like (t:T) => U, then (u:U) => V, etc. Nevermind!
type Ops<T, R, N> = [
(x: T) => N[0],
...<n>((x: N[n]) => N[n + 1]),
(x: N.last) => R,
];
function pipe<T>(init: T): T;
function pipe<R, T, Ops>(init: T, ...ops: ...Ops<T, R>): R;