Skip to content

Commit

Permalink
fix: Remove default value from tuple().
Browse files Browse the repository at this point in the history
  • Loading branch information
milesj committed Aug 29, 2021
1 parent 96905e2 commit 97ec98b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 13 deletions.
1 change: 1 addition & 0 deletions optimal/src/schemas/shape.ts
Expand Up @@ -26,6 +26,7 @@ function validateType(): Criteria<unknown> | void {
skipIfNull: true,
validate(value, path) {
if (value === undefined) {
// Will be built from its items
return {};
}

Expand Down
9 changes: 7 additions & 2 deletions optimal/src/schemas/tuple.ts
Expand Up @@ -16,20 +16,25 @@ function validateType(): Criteria<unknown[]> | void {
return {
skipIfNull: true,
validate(value, path) {
if (value === undefined) {
// Will be built from its items
return [];
}

invariant(Array.isArray(value), 'Must be a tuple.', path);

return value;
},
};
}

export function tuple<T extends unknown[] = unknown[]>(
schemas: InferTupleItems<T>,
defaultValue?: T,
): TupleSchema<T> {
return createSchema<TupleSchema<T>>({
// @ts-expect-error Ignore this, it's safe
cast: createArray,
criteria: { ...commonCriteria, ...tupleCriteria },
defaultValue,
type: 'tuple',
validateType,
}).of(schemas);
Expand Down
38 changes: 27 additions & 11 deletions optimal/tests/schemas/tuple.test.ts
Expand Up @@ -18,17 +18,14 @@ describe('tuple()', () => {
});

runCommonTests<Tuple>(
(defaultValue) =>
tuple(
[
array().of(string()),
bool(true),
number(1).between(0, 5),
object().of(number()),
string('foo').oneOf(['foo', 'bar', 'baz']),
],
defaultValue,
),
() =>
tuple([
array().of(string()),
bool(true),
number(1).between(0, 5),
object().of(number()),
string('foo').oneOf(['foo', 'bar', 'baz']),
]),
[['a', 'b', 'c'], true, 3, { a: 1 }, 'baz'],
{
defaultValue: [[], false, 1, {}, 'foo'],
Expand Down Expand Up @@ -97,6 +94,25 @@ describe('tuple()', () => {
}).toThrow('Null is not allowed.');
});

it('returns the default value from its items when undefined is passed', () => {
expect(schema.validate(undefined)).toEqual([[], true, 1, {}, 'foo']);

const testSchema = tuple<Tuple>([
array(['abc']).of(string()),
bool(true),
number(3).between(0, 5),
object({ foo: 123 }).of(number()),
string('baz').oneOf(['foo', 'bar', 'baz']),
]);

expect(testSchema.validate(undefined)).toEqual([['abc'], true, 3, { foo: 123 }, 'baz']);
});

it('returns the default value from its items when an empty array is passed', () => {
// @ts-expect-error Invalid type
expect(schema.validate([])).toEqual([[], true, 1, {}, 'foo']);
});

describe('production', () => {
it(
'doesnt error if a non-tuple is passed',
Expand Down

0 comments on commit 97ec98b

Please sign in to comment.