onExcessProperty does not work with numberFromString transformer
parischap opened this issue Β· comments
π Bug report
Current Behavior
S.NumberFromString
does not throw when non numeric characters are provided at the end of the input string
Expected behavior
Should throw as 1AB
is not a string that represents a number.
Reproducible example
import * as S from '@effect/schema/Schema';
// const schema: S.Schema<string, number>
const schema = S.NumberFromString;
const parse = S.parse(schema);
// Success
console.log(parse('1AB'));
Suggested solution(s)
I think the issue is linked to the use of parseFloat as it can accept a string that contains non numeric stuff at the end.
A possible "clumsy" correction could be:
export const NumberFromString = S.transformResult(
S.string,
S.number,
(s) =>
pipe(s, Number, (n) =>
n === 0 && Str.trim(s) === '' ? PR.failure(PR.type(S.number.ast, s)) : PR.success(n)
),
(n) => PR.success(n.toString())
);
Additional context
Sorry, the name of the bug is incorrect. The current name of the bug is only one of the consequences of the bug described here . Below is the code related to the original bug that finally led me to this one:
import * as E from '@effect/data/Either';
import * as PR from '@effect/schema/ParseResult';
import * as S from '@effect/schema/Schema';
import { formatErrors } from '@effect/schema/TreeFormatter';
const print = <A>(e: E.Either<PR.ParseError, A>) => {
if (E.isLeft(e)) {
console.log(formatErrors(e.left.errors));
} else console.log(e);
};
const schema = S.NumberFromString;
const parse = S.parseEither(schema);
// { _tag: 'Right', right: 1 }
print(parse('1AB', { onExcessProperty: 'error' }));
Your environment
Which versions of @effect/schema
are affected by this issue? Did this work in previous versions of @effect/schema
?
Software | Version(s) |
---|---|
@effect/schema | 0.19.3 |
TypeScript | 5.1.0-tsplus.20230423 |