Home > other >  Is it posible to override existing property's type in typescript?
Is it posible to override existing property's type in typescript?

Time:01-20

I'm using i18next with failback language, so resolvedLanguage to me is certain like 'zh'|'en', is it possible to override resolvedLanguage's type (originally type as string)? so that when i use this value i don't have to use as 'zh'|'en' to convert it's type.

CodePudding user response:

Overriding module type is a little trickier than extending its interface, because we cannot use declaration merging. Still we can do a little workaround instead.

i18next.d.ts:

declare module 'i18next' {
  import { i18n } from 'i18next/index'; // Original interface is imported from i18next/index to avoid circular imports.
  type I18nWithLanguages = i18n & {
    resolvedLanguage: 'zh' | 'en';
  };
  declare const i18WithLanguages: I18nWithLanguages;
  export default i18WithLanguages;
};

We just import original i18n interface, modify to our needs and export it again.

Effect:

// Error: Type '"pl"' is not assignable to type '"zh" | "en"'
i18n.resolvedLanguage = 'pl';
  •  Tags:  
  • Related