From 677755c60039bf62cff444ae5e70c974b4ee7818 Mon Sep 17 00:00:00 2001 From: Marco Pasqualetti <24919330+marcalexiei@users.noreply.github.com> Date: Fri, 12 Apr 2024 12:28:24 +0200 Subject: [PATCH] test(types): add context + enum scenario (#2173) --- test/typescript/custom-types/t.test.ts | 53 ++++++++++++++++++++++---- tsconfig.json | 2 +- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/test/typescript/custom-types/t.test.ts b/test/typescript/custom-types/t.test.ts index 502f7405..0c71a36a 100644 --- a/test/typescript/custom-types/t.test.ts +++ b/test/typescript/custom-types/t.test.ts @@ -140,17 +140,56 @@ describe('t', () => { expectTypeOf(t('place', { ordinal: true, count: 4 })).toBeString(); }); - it('should work with context', () => { + describe('context', () => { const t = (() => '') as TFunction<'ctx'>; - expectTypeOf(t('dessert', { context: 'cake' })).toEqualTypeOf<'a nice cake'>(); + it('should work with basic usage', () => { + expectTypeOf(t('dessert', { context: 'cake' })).toEqualTypeOf<'a nice cake'>(); - // context + plural - expectTypeOf(t('dessert', { context: 'muffin', count: 3 })).toMatchTypeOf(); + // context + plural + expectTypeOf(t('dessert', { context: 'muffin', count: 3 })).toMatchTypeOf(); - // @ts-expect-error - // valid key with invalid context - assertType(t('foo', { context: 'cake' })); + // @ts-expect-error + // valid key with invalid context + assertType(t('foo', { context: 'cake' })); + }); + + it('should work with enum as a context value', () => { + enum Dessert { + CAKE = 'cake', + MUFFIN = 'muffin', + } + + const ctx = Dessert.CAKE; + + expectTypeOf(t('dessert', { context: ctx })).toMatchTypeOf(); + + enum DessertMissingValue { + COOKIE = 'cookie', + CAKE = 'cake', + MUFFIN = 'muffin', + ANOTHER = 'another', + } + + const ctxMissingValue = DessertMissingValue.ANOTHER; + + // @ts-expect-error Dessert.ANOTHER is not mapped so it must give a type error + expectTypeOf(t('dessert', { context: ctxMissingValue })).toMatchTypeOf(); + }); + + it('should work with string union as a context value', () => { + expectTypeOf( + t('dessert', { context: 'muffin' as 'muffin' | 'cake' }), + ).toMatchTypeOf(); + }); + + // @see https://github.com/i18next/i18next/issues/2172 + // it('should trow error with string union with missing context value', () => { + // expectTypeOf( + // // @ts-expect-error + // t('dessert', { context: 'muffin' as 'muffin' | 'cake' | 'pippo' }), + // ).toMatchTypeOf(); + // }); }); it('should work with false plural usage', () => { diff --git a/tsconfig.json b/tsconfig.json index 9d3a4459..ad1d0259 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,7 +16,7 @@ "allowSyntheticDefaultImports": true, /** - * setting this to `false` to throw an error when d.ts file trow an error + * setting this to `false` to throw an error when d.ts file have invalid code * @see https://github.com/i18next/i18next/issues/2168 */ "skipLibCheck": false