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

proposal for data constructor defaults #2443

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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 packages/effect/src/Data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,3 +451,31 @@ export const TaggedError = <Tag extends string>(tag: Tag): new<A extends Record<
;(Base.prototype as any).name = tag
return Base as any
}

/**
* @since 2.0.0
* @category constructors
*/
export const addDefaults: <Args, Defaults extends { [K in keyof Args]?: () => Args[K] }, Out extends object>(
newable: new(args: Args) => Out,
defaults: Defaults
) => new(
args: Omit<Args, keyof Defaults> & { [K in keyof Args as K extends keyof Defaults ? K : never]?: Args[K] }
) => Out = (
newable,
defaults
) => {
return class extends (newable as any) {
constructor(args: any) {
super({
...args,
...Object.entries(defaults).reduce((acc, [cur, v]) => {
if (!(cur in args)) {
acc[cur] = (v as any)()
}
return acc
}, {} as Record<string, any>)
})
}
} as any
}
10 changes: 10 additions & 0 deletions packages/effect/test/Effect/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,14 @@ describe("Effect", () => {
class MessageError extends Data.TaggedError("MessageError")<{}> {}
assert.deepStrictEqual(new MessageError().toJSON(), { _tag: "MessageError" })
})

it.it("withDefaults", () => {
class TestError extends Data.addDefaults(
Data.TaggedError("TestError")<{ a: string; b: number }>,
{ b: () => 1 }
) {}

assert.deepStrictEqual(new TestError({ a: "hello" }).toJSON(), { _tag: "TestError", a: "hello", b: 1 })
assert.deepStrictEqual(new TestError({ a: "hello", b: 2 }).toJSON(), { _tag: "TestError", a: "hello", b: 2 })
})
})