gcanti / newtype-ts

Implementation of newtypes in TypeScript
https://gcanti.github.io/newtype-ts/
MIT License
578 stars 14 forks source link

readme: fix integer detection #18

Closed tatchi closed 5 years ago

tatchi commented 5 years ago

Hello,

Thanks for this great library :) I was playing around with the examples I encountered something I was not expecting:

interface Integer extends Newtype<{ readonly Integer: unique symbol }, number> {}

const isInteger = (n: number) => n % 1 === 0;

// prismInteger: Prism<number, Integer>
const prismInteger = prism<Integer>(isInteger);

const add1 = (n: Integer) => prismInteger.reverseGet(n) + 1;

prismInteger.getOption(undefined).map(add1); // None
prismInteger.getOption(null).map(add1); // Some(1)

I would have expected the null example to give me None as for the undefined one.

Seems like it's because null % 1 === 0. I fixed it by using Number.isInteger function.

gcanti commented 5 years ago

@tatchi AFAIK passing null doesn't even type-checks

prismInteger.getOption(null) // Argument of type 'null' is not assignable to parameter of type 'number'
tatchi commented 5 years ago

I don't get this behaviour:

https://codesandbox.io/s/k9o5626nj3

Am I doing something wrong?

gcanti commented 5 years ago

maybe a setup issue, the prismInteger value in your link is inferred as any instead of Prism<number, Integer>

gcanti commented 5 years ago

@tatchi anyway Number.isInteger is more standard so I'm fine with this change, thank you