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/zod contracts lose branding #513

Merged
merged 5 commits into from
Sep 4, 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
5 changes: 5 additions & 0 deletions .changeset/quick-adults-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@farfetched/zod": patch
---

Fix `zodContracts` type inference for branded types
13 changes: 13 additions & 0 deletions packages/zod/src/__tests__/contract.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,17 @@ describe('zodContract', () => {
>();
}
});

test('branded type', () => {
const BrandedContainer = zod.object({
branded: zod.string().brand<'Branded'>(),
});
const brandedContract = zodContract(BrandedContainer);

const smth: unknown = { branded: 'branded' };

if (brandedContract.isData(smth)) {
expectTypeOf(smth).toEqualTypeOf<zod.infer<typeof BrandedContainer>>();
}
});
});
8 changes: 5 additions & 3 deletions packages/zod/src/zod_contract.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type ZodType } from 'zod';
import { type ZodType, type TypeOf } from 'zod';
import { type Contract } from '@farfetched/core';

/**
Expand All @@ -7,8 +7,10 @@ import { type Contract } from '@farfetched/core';
*
* @param {ZodType} data Zod Contract for valid data
*/
function zodContract<D>(data: ZodType<D>): Contract<unknown, D> {
function isData(prepared: unknown): prepared is D {
function zodContract<T extends ZodType<any, any, any>>(
data: T
): Contract<unknown, TypeOf<T>> {
function isData(prepared: unknown): prepared is T {
return data.safeParse(prepared).success;
}

Expand Down
Loading