Skip to content

Commit

Permalink
fix: Fix isPartial allowing unexpected keys
Browse files Browse the repository at this point in the history
  • Loading branch information
NiGhTTraX committed May 22, 2024
1 parent 6ab4b60 commit cc0b881
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
4 changes: 2 additions & 2 deletions src/matchers/is-partial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ const deepPrintObject = (value: unknown) =>
// T is not constrained to ObjectType because of
// https://github.com/microsoft/TypeScript/issues/57810,
// but K is to avoid inferring non-object partials
export const isPartial = <T, K extends DeepPartial<T> & ObjectType>(
partial: K
export const isPartial = <T, K extends DeepPartial<T>>(
partial: K extends ObjectType ? K : never
): TypeMatcher<T> =>
matches((actual) => isMatch(actual, partial), {
toString: () => `Matcher<object>(${printValue(deepPrintObject(partial))})`,
Expand Down
31 changes: 22 additions & 9 deletions tests/types.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,12 @@ it('type safety', () => {
function partialSafety() {
const number = (x: number) => x;
number(
It.isPartial(
// @ts-expect-error non-object can't be partial-ed
{ toString: () => 'bar' }
)
// @ts-expect-error non-object can't be partial-ed
It.isPartial({ toString: () => 'bar' })
);
number(
It.isPartial(
// @ts-expect-error non-object
42
)
// @ts-expect-error non-object
It.isPartial(42)
);

const numberArray = (x: number[]) => x;
Expand All @@ -77,7 +73,12 @@ it('type safety', () => {
// @ts-expect-error wrong nested property type
It.isPartial({ foo: { bar: 'boo' } })
);

nestedObject(
It.isPartial({
// @ts-expect-error unexpected key
unexpected: 42,
})
);
nestedObject(
It.isPartial({
// @ts-expect-error because TS can't infer the proper type
Expand All @@ -91,9 +92,21 @@ it('type safety', () => {
}
const withInterface = (x: InterfaceType) => x;
withInterface(It.isPartial({ foo: 'bar' }));
withInterface(
It.isPartial(
// @ts-expect-error unexpected key
{ unexpected: 42 }
)
);

const object = (x: { foo: number }) => x;
object(It.isPartial({ foo: It.isNumber() }));
object(
It.isPartial(
// @ts-expect-error unexpected key
{ unexpected: It.isNumber() }
)
);
object(
It.isPartial({
// @ts-expect-error wrong nested matcher type
Expand Down

0 comments on commit cc0b881

Please sign in to comment.