Typescript:通过模块增强在内部对象上添加属性

Zod*_*ddo 5 typescript module-augmentation

考虑外部 (npm) 模块extmod在其声明文件中公开以下接口:

interface Options {
  somevar?: string;
  suboptions?: {
    somesubvar?: string;
  };
}
Run Code Online (Sandbox Code Playgroud)

如何通过模块增强somesubvar2在内部添加属性?suboptions

我在文件中尝试了以下操作extmod.d.ts

declare module 'extmod' {
  interface Options {
    suboptions?: {
      somesubvar2?: string;
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

但它会引发以下错误:

error TS2687: All declarations of 'suboptions' must have identical modifiers.
Run Code Online (Sandbox Code Playgroud)
error TS2717: Subsequent property declarations must have the same type.  Property 'suboptions' must be of type '<SNIP>', but here has type '{ somesubvar2: string; }'.
Run Code Online (Sandbox Code Playgroud)

Józ*_*cki -1

如何通过模块增强在子选项内添加属性 somesubvar2 ?

在您的示例中,您将类型suboptions从更改<SNIP>{ somesubvar2: string; }

您可以<SNIP>使用附加属性修补类型。