My definition of the type and the variable is as follows: the LOCALES_KEYS
variable is an enum
export const resources = {
'ja-JP': jaJP,
'zh-TW': zhTW,
'en-US': enUS,
'zh-CN': zhCN,
};
export type Lng = keyof typeof resources;
export type Resources = {
[K in Lng]: (typeof resources)[K] & {
[P in LOCALES_KEYS]: P extends keyof (typeof resources)[K]
? (typeof resources)[K][P]
: '';
};
};
export interface AppContextData extends DefaultData {
language?: Lng;
t: <T extends LOCALES_KEYS>(
key: T,
) => Resources[keyof typeof resources][T];
}
const t: AppContextData['t'] = (key) => {
const lang: Lng = 'en-US';
return (resources as Resources)[lang][key];
};
When using the t
function, everything works fine. However, when using t
with non-empty assertions, the generic inference doesn't work as expected
t(LOCALES_KEYS.AVATAR); // The type when hovering over the t function is: const t: <LOCALES_KEYS.AVATAR>(key: HOME_KEYS.AVATAR, options?: TOptions) => "" | "Avatar" | "头像"
// Nonempty assertion
t!(LOCALES_KEYS.AVATAR);
// The type when hovering over the t function is: const t: <T extends LOCALES_KEYS>(key: T, options?: TOptions) => (({
// readonly argots: "Argots";
// readonly meta_desc: "A free chat platform that encrypts conversation information throughout
// the process to protect your security and privacy. No information is collected from you and no
// permissions are required from you. End of chat Clear all records";
// ... 19 more ...;
// readonly Invitation_description: "Each invitation link can only invite one user, and the
// invitation is invalid after success";
// } & {
// ...;
The reason for this behavior is unclear to me. I attempted to search for relevant information on Google without success.
This code snippet is reproducible - Using '! ' affects generic inference
const t: <T>(val: T) => T = (val) => {
return val;
};
t('111'); // const t: <"111">(val: "111") => "111"
t!('111'); // const t: <T>(val: T) => T