Type inference problems in typescript ?
When i have this code in intellij, hovering over the bind method to get a signature gives me a wrong return type.
Furthermore, adding static types does not even seem to solve this. The typescript compiler handles this correctly, and visual studio code gives me a correct type.
Am i missing something ?
class Either<L, R> {
constructor(
private type: 'Left' | 'Right',
private left?: L,
private right?: R
) { }
static right<L, R>(r: R) {
return new Either<L, R>('Right', null, r);
}
static left<L, R>(l: L) {
return new Either<L, R>('Left', l, null);
}
public bind<T>(f: (r: R) => Either<L, T>) {
return this.type === 'Right' ?
f(this.right) :
Either.left<L, T>(this.left);
}
}
Please sign in to leave a comment.
Your code doesn't compile - there are multiple type mismatch errors:
Error:(11, 42) TS2345: Argument of type 'null' is not assignable to parameter of type 'L | undefined'.
Error:(15, 44) TS2345: Argument of type 'null' is not assignable to parameter of type 'R | undefined'.
Error:(21, 15) TS2345: Argument of type 'R | undefined' is not assignable to parameter of type 'R'.
Type 'undefined' is not assignable to type 'R'.
Error:(22, 31) TS2345: Argument of type 'L | undefined' is not assignable to parameter of type 'L'.
Type 'undefined' is not assignable to type 'L'.
Please can you provide a valid code sample that shows up the issue?
Hi Elena,
Thats probably because you have strictNullChecks enabled. Can you disablestrictNullChecks and retry ?
I can also provide you with another implementation which does not use nulls, the code sample above is actually a simplified version to show the issue.
The following is extracted from what we use in production and compiles with strictNullChecks.
Hovering over the bind method shows the following: (for some reason the L is inferred incorrectly ...)
I was unable to take a screenshot while hovering over the bind method in vscode, the popup dissapears upon pressing screenshot.
So i created an instance then was able to take a screenshot:
Here you can see the return type is a Either<L, T> (L remains string and does not become any)
thanks for details, logged as https://youtrack.jetbrains.com/issue/WEB-29593. Please vote for it to be notified on any progress
Awesome, thanks !