Skip to content

Commit

Permalink
Merge pull request #10 from airtoxin/interface
Browse files Browse the repository at this point in the history
Add Interface type
  • Loading branch information
airtoxin committed Mar 1, 2021
2 parents bba9f08 + 1f23486 commit 38624a4
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Codec/Interface.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Interface } from "./Interface";
import { GetType, optional, Right, string } from "purify-ts";

describe("Interface", () => {
const c = Interface({ str: string, ops: optional(string) });

it("should return interface Codec", () => {
expect(c.decode({ str: "foo" })).toEqual(Right({ str: "foo" }));
// compile test
const v: GetType<typeof c> = { str: "foo" };
expect(v).toEqual({ str: "foo" });
});

it("should return the type accepting object that its optional field to be not defined", () => {
// compile test: 'ops' field not defined but acceptable
// `GetType<typeof c>` equals to `{ str: string, ops?: string | undefined }`
const v: GetType<typeof c> = { str: "foo" };
expect(v).toEqual({ str: "foo" });
});
});
24 changes: 24 additions & 0 deletions src/Codec/Interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Codec, GetType } from "purify-ts";

export const Interface = <T extends Record<string, Codec<any>>>(
properties: T
): Codec<
{
[K in keyof ({
[K in keyof Pick<
T,
{
[K in keyof T]-?: undefined extends GetType<T[K]> ? never : K;
}[keyof T]
>]: GetType<T[K]>;
} &
{
[K in keyof Pick<
T,
{
[K in keyof T]-?: undefined extends GetType<T[K]> ? K : never;
}[keyof T]
>]?: Exclude<GetType<T[K]>, undefined>;
})]: GetType<T[K]>;
}
> => Codec.interface(properties) as any;
1 change: 1 addition & 0 deletions src/Either/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./sequenceWeak";
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./Codec";
export * from "./Either";

0 comments on commit 38624a4

Please sign in to comment.