使 FormattedMessage 中的 id 从 react-intl 继承自自定义 TypeScript 接口以启用 VS IntelliSense 和类型检查

Make id in FormattedMessage from react-intl inherit from a custom TypeScript interface to enable VS IntelliSense and type checking

鉴于 react-localization 没有日期和数字格式,并且严重依赖于一个开发人员,我们决定切换到 react-intl,因为从 运行 来看它似乎更安全。

https://github.com/stefalda/react-localization/graphs/contributors

我们之前的代码是这样的:

localizationService.ts

import LocalizedStrings from 'react-localization';

import svSE from './languages/sv-SE';
import enUS from './languages/en-US';
import arSA from './languages/ar-SA';

export default new LocalizedStrings({
    svSE,
    enUS,
    arSA
});

ILanguageStrings.ts

export interface ILanguageStrings {
    appName: string
    narration: string
    language: string
}

zh-US.ts

import { ILanguageStrings } from '../ILanguageStrings';

const language: ILanguageStrings = {
    appName: "Our App",
    narration: "Narration",
    language: "Language"
}

export default language;

然后可以导入本地化,ILanguageStrings 在 Visual Studio 中通过 IntelliSense 可见,并由 TypeScript 验证。

import localization from '../services/localizationService';

但是使用 react-intl id 中的 FormattedMessagestring | number | undefined。我们仍然使用语言文件,所以我们如何确保 idILanguageStrings 中而不破坏 react-intl 中的原始类型定义?

我尝试使用 TypeScript 声明合并和合并接口,但我只能在那里添加新成员而不能更改 ID 属性。 “有效”字符串也未被视为正确。

react-app-env.d.ts:

import * as reactIntl from 'react-intl';

declare module 'react-intl' {
    export interface MessageDescriptor {
        id?: ILanguageStrings;
        idTest: ILanguageStrings 
    }
}

https://github.com/microsoft/TypeScript/issues/10859

https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces

我之前在使用 react-intltypescript 时遇到了同样的问题。我的解决方案只是创建一个包装器组件,为 id 提供适当的类型。 id 类型应该是 keyof 支持最多的语言配置对象。

假设文件./languages/en-US的内容是这样的

{
  "AUTH.GENERAL.FORGOT_BUTTON": "Forgot Password",
  "AUTH.LOGIN.TITLE": "Login Account",
  "AUTH.FORGOT.TITLE": "Forgotten Password?",
  "AUTH.REGISTER.TITLE": "Sign Up",
  "AUTH.VALIDATION.INVALID": "{name} is not valid",
  "AUTH.VALIDATION.REQUIRED": "{name} is required",
  "AUTH.VALIDATION.NOT_FOUND": "The requested {name} is not found",
  "AUTH.VALIDATION.INVALID_LOGIN": "The login detail is incorrect",
  "AUTH.VALIDATION.REQUIRED_FIELD": "Required field",
  "AUTH.VALIDATION.INVALID_FIELD": "Field is not valid",
  "MENU.DASHBOARD": "Dashboard",
  "MENU.PRODUCT": "Product",
  "TOPBAR.GREETING": "Hi,",
  ...
}

I18nProvider.tsx

import React from "react";
import { IntlProvider } from "react-intl";
import svSE from './languages/sv-SE';
import enUS from './languages/en-US';
import arSA from './languages/ar-SA';

// In this example, english has the most support, so it has all the keys
export type IntlMessageID = keyof typeof enUS;

export default function I18nProvider({ children }) {
  return (
    <IntlProvider locale="en" messages={enMessages}>
      {children}
    </IntlProvider>
  );
}

FormattedMessage.tsx

import React from "react";
import { FormattedMessage as ReactFormattedMessage } from "react-intl";
import { IntlMessageID } from "./I18nProvider";

type FormattedMessageProps = {
  id?: IntlMessageID;
  defaultMessage?: string;
  values?: Record<string, React.ReactNode>;
  children?: () => React.ReactNode;
};

export default function FormattedMessage(props: FormattedMessageProps) {
  return <ReactFormattedMessage {...props} />;
}

用法

import React from "react";
import I18nProvider from "./I18nProvider";
import FormattedMessage from "./FormattedMessage";

export default function App() {
  return (
    <I18nProvider>
      <div className="App">
        <FormattedMessage id="..." />
      </div>
    </I18nProvider>
  );
}

这是结果

现场演示

在下面的演示中,您可以通过按 Ctrl + Space

在编辑器中触发 IntelliSense

我的第一个想法和@NearHuscarl 一样

然而,我发现文档中有一节是关于这个的:

https://formatjs.io/docs/react-intl#typing-message-ids-and-locale

您可以使用全局声明来扩充消息 id 的类型

declare global {
  namespace FormatjsIntl {
    interface Message {
      ids: keyof typeof messages
    }
  }
}