-
Notifications
You must be signed in to change notification settings - Fork 419
Description
Describe the bug
When strictFunctionTypes and strictNullChecks are enabled in TSConfig (quite often as nowadays most TS projects have strict enabled), the Translator interface cannot be implemented correctly.
strictFunctionTypes requires function parameters to be contravariant and function return types to be covariant.
strictNullChecks causes string and string | undefined to be treated as different types.
Because the function implementation must match all 3 overloads:
jsonforms/packages/core/src/store/i18nTypes.ts
Lines 4 to 8 in 6bbfbb3
| export type Translator = { | |
| (id: string, defaultMessage: string, values?: any): string; | |
| (id: string, defaultMessage: undefined, values?: any): string | undefined; | |
| (id: string, defaultMessage?: string, values?: any): string | undefined; | |
| }; |
- For the
defaultMessageparameter, the only type that is contravariant withstring,undefinedandstring | undefinedisstring | undefined - For the return type, the only type that is covariant with
stringandstring | undefinedisstring
The only implementation that meets both is:
(id: string, defaultMessage?: string, values?: any) => string;which means that the defaultMessage can be undefined, but the return value cannot be undefined.
This makes it impossible to implement the note in https://jsonforms.io/docs/i18n/#defaultmessage:
If the
defaultMessageisundefined, you should also returnundefinedif there is no translation for the given key. Returning an empty string (or something similar) instead may result in undesired behavior. JSON Forms will useundefinedwhen the message could be skipped or another more generic key could be tried.
Expected behavior
Able to implement the Translator interface as:
(id: string, defaultMessage?: string, values?: any) => string | undefined;Steps to reproduce the issue
- Go to https://github.com/eclipsesource/jsonforms/blob/v3.7.0/packages/examples/tsconfig.json
- Set strictFunctionTypes and strictNullChecks to
trueincompilerOptions - Build the project
- See that packages/examples/src/examples/i18n.ts fails to compile
jsonforms/packages/examples/src/examples/i18n.ts
Lines 102 to 104 in 6bbfbb3
export const translate: Translator = (key: string, defaultMessage: string) => { return get(translations, key) ?? defaultMessage; };
Screenshots
No response
Which Version of JSON Forms are you using?
3.7.0
Package
Core
Additional context
No response