jklmli / monapt

Options, Tries, and Futures for JavaScript / TypeScript
MIT License
172 stars 13 forks source link

Infer type of None #11

Closed OliverJAsh closed 8 years ago

OliverJAsh commented 8 years ago

Is it possible to infer the type of None when used alongside Some?

E.g. in Scala:

scala> def x = (a: Int) => if (a > 5) Some(5) else None
x: Int => Option[Int]

In TypeScript:

const x = (a: number) => (a > 5) ? Option(5) : None

x here is of type (a: number) => Option<any>, because None is typed as Option<any>.

I wonder if it's possible to infer the generic type of None here from the usage of Option in the same function?

jklmli commented 8 years ago

This should be possible once TypeScript 2.0 lands (soon!).

None being typed as Option<any> is wrong, because any is the supertype of all types, rather than the subtype of all types.

Typescript 2.0 is getting a never type that is a subtype of all types. This should allow the compiler to inference things as you'd expect.

OliverJAsh commented 8 years ago

Will this mean you can do the equivalent of def x = (a: Int) => if (a > 5) Some(5) else None? E.g.

x = (a: number): Option<number> => if (a > 5) { Option(5) } else { None }

Currently I have to do

x = (a: number): Option<number> => if (a > 5) { Option(5) } else { None as Option<number> }

jklmli commented 8 years ago

Yes, TypeScript 2.0 should allow the shorter form =)