Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Don't exclude null from oneOf return type #719

Merged
merged 1 commit into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/__tests__/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,34 @@ describe('types', () => {
expectType<typeof value>(true);
expectType<typeof value>('foo');
});

test('nullable', () => {
const value = types.oneOf([types.string(), types.null()], { required: true });

expect(value).toEqual(
expect.objectContaining({
$required: true,
oneOf: [
{
$required: true,
type: 'string',
},
{
$required: true,
type: 'null',
},
],
})
);

expectType<string | null>(value);
// @ts-expect-error `value` should not be `number`
expectType<number>(value);
// @ts-expect-error `value` should not be `undefined`
expectType<undefined>(value);
expectType<typeof value>('foo');
expectType<typeof value>(null);
});
});
});
});
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export function objectGeneric<Property, Options extends ObjectOptions>(
export function oneOf<Types extends any[], Options extends GenericOptions>(
types: Types,
options?: Options
): GetType<NonNullable<Types[number]>, Options> {
): GetType<Exclude<Types[number], undefined>, Options> {
const { required } = options || {};

// eslint-disable-next-line @typescript-eslint/no-unsafe-return
Expand All @@ -226,7 +226,7 @@ export function oneOf<Types extends any[], Options extends GenericOptions>(
$required: true,
}))
: types,
} as unknown as GetType<NonNullable<Types[number]>, Options>;
} as unknown as GetType<Exclude<Types[number], undefined>, Options>;
}

function createSimpleType<Type>(type: BSONType) {
Expand Down