-
-
Notifications
You must be signed in to change notification settings - Fork 278
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(i18n): add better types to our custom defineMessages (#1192)
- Loading branch information
1 parent
9a59529
commit 66948b4
Showing
3 changed files
with
24 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,26 @@ | ||
import { defineMessages as intlDefineMessages } from 'react-intl'; | ||
|
||
export default function defineMessages( | ||
type Messages<T extends Record<string, string>> = { | ||
[K in keyof T]: { | ||
id: string; | ||
defaultMessage: T[K]; | ||
}; | ||
}; | ||
|
||
export default function defineMessages<T extends Record<string, string>>( | ||
prefix: string, | ||
messages: Record<string, string> | ||
) { | ||
const modifiedMessages: Record< | ||
string, | ||
{ id: string; defaultMessage: string } | ||
> = {}; | ||
for (const key of Object.keys(messages)) { | ||
modifiedMessages[key] = { | ||
id: prefix + '.' + key, | ||
messages: T | ||
): Messages<T> { | ||
const keys: (keyof T)[] = Object.keys(messages); | ||
const modifiedMessagesEntries = keys.map((key) => [ | ||
key, | ||
{ | ||
id: `${prefix}.${key as string}`, | ||
defaultMessage: messages[key], | ||
}; | ||
} | ||
}, | ||
]); | ||
const modifiedMessages: Messages<T> = Object.fromEntries( | ||
modifiedMessagesEntries | ||
); | ||
return intlDefineMessages(modifiedMessages); | ||
} |