Skip to content

Commit 4a08a96

Browse files
authored
Improve type consistency (#13)
* ✨ enhance Try class with TypeScript type safety in default method and add new test case Signed-off-by: w01fgang <sumin@unix-center.ru> * 🔖 bump version to 0.0.6 and add typecheck script Signed-off-by: w01fgang <sumin@unix-center.ru> --------- Signed-off-by: w01fgang <sumin@unix-center.ru>
1 parent 11c544d commit 4a08a96

3 files changed

Lines changed: 22 additions & 3 deletions

File tree

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@power-rent/try-catch",
3-
"version": "0.0.5",
3+
"version": "0.0.6",
44
"description": "A TypeScript utility for simplified async error handling with Sentry integration",
55
"main": "dist/index.js",
66
"module": "dist/esm/index.js",
@@ -29,6 +29,7 @@
2929
"test": "vitest run",
3030
"test:watch": "vitest",
3131
"clean": "rm -rf dist",
32+
"typecheck": "tsc --noEmit",
3233
"prepublishOnly": "npm run clean && npm run build && npm run test"
3334
},
3435
"keywords": [

src/__tests__/Try.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,4 +216,16 @@ describe('Try', () => {
216216

217217
await expect(exec).rejects.toThrow('validation error');
218218
});
219+
220+
it('should not give typescript error', async () => {
221+
const params = { parameterKey: 'alpha' };
222+
223+
const result = await new Try(throwingFunction, params)
224+
.default({ ok: true })
225+
.value();
226+
227+
expect(result).not.toBe(undefined);
228+
expect(() => result.ok).not.toThrow(TypeError);
229+
expect(Sentry.captureException).not.toHaveBeenCalled();
230+
});
219231
});

src/nextjs/index.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,14 @@ export class Try<T, TArgs extends readonly Record<string, any>[] = Record<string
202202
* .value(); // Returns null if findUser throws
203203
* ```
204204
*/
205-
default<Return>(defaultValue: Return): Try<T, TArgs> {
206-
return this.setConfig({ defaultValue });
205+
default<D>(defaultValue: D): Omit<typeof this, 'value'> & { value(): Promise<Awaited<T> | D> } {
206+
type WithGuaranteedValue = Omit<typeof this, 'value'> & {
207+
value(): Promise<Awaited<T> | D>;
208+
};
209+
210+
// Cast is safe: runtime shape is unchanged; this only narrows the static
211+
// return type information for the `value` method.
212+
return this.setConfig({ defaultValue }) as unknown as WithGuaranteedValue;
207213
}
208214

209215
/**

0 commit comments

Comments
 (0)