代码之家  ›  专栏  ›  技术社区  ›  Kristi Jorgji

当名称中包含特殊字符时,如何扩展外部Typescript库接口?

  •  0
  • Kristi Jorgji  · 技术社区  · 1 年前

    我知道这是一个已经存在的问题,但我找不到包含特殊字符的命名空间 @ / .

    用例:

    我想延长 import { Strapi } from '@strapi/strapi'; 这个 Strapi 来自@strapi/strapi的接口。 它不见了 webhookStore 以及我想添加的其他属性。

    第一种方法

    我创建了 extentions.d.ts 具有以下内容

    declare global {
        namespace '@strapi/strapi' {
            interface Strapi {
                webhookStore: {
                    c: any;
                };
            }
        }
    }
    

    但它不起作用。Typescript抱怨 TS1003: Identifier expected. 用于'@strapi/strapi'

    enter image description here

    我已经成功地扩展了具有单个名称的接口,如“Stripe”等,但在这种情况下,我不知道如何实现它。

    没有@strapi/strapi,我无法使用 ' 包装,因为这将是编译错误。

    第二种方法-模块扩充/合并

    我也试过 module augmentation 这里也有人提出,但没有奏效。

    type WebhookStore = {
        findWebhooks: () => void;
    };
    
    declare module '@strapi/strapi' {
        interface Strapi {
            webhookStore: WebhookStore;
        }
    }
    

    这是对Strapi接口的重新定义,编辑器PhpStorm都只承认webhookStore是唯一的属性!(正在丢失库本身导出的其他文件的信息)。同样无法编译,因为ts编译器再次只识别webhookStore。它正在重新定义,没有发生合并

    yarn build 哪是整理和编纂

    5 import { factories } from '@strapi/strapi';
               ~~~~~~~~~
    src/api/tag/routes/tag.ts:5:10 - error TS2305: Module '"@strapi/strapi"' has no exported member 'factories'.
    
    
    2 回复  |  直到 1 年前
        1
  •  1
  •   0xts    1 年前

    您想要做的叫做声明合并/模块扩充。你是怎么做到的 augment a module -

    import API from "@strapi/strapi";
    
    declare module "@strapi/strapi/lib/types/core/index" {
        interface Strapi {
            webhookStore: { c: any }
        }
    }
    
    declare global {
      namespace Strapi {
        export type Webhook = { c: any };
      }
    }
    
    const store = API({}).webhookStore
     //   ^? const store: { c: any; }
    
    let a: Strapi.Webhook
    //  ^? let a: Strapi.Webhook
    
    

    这是一个 link to the playground ;

        2
  •  0
  •   Jörg W Mittag    1 年前

    不可能有 namespace 命名的 @strapi/strapi ,因为这既不是有效的TypeScript标识符,也不是有效的ECMAScript标识符。

    命名空间 s用于表示全局ECMAScript对象,因此需要是有效的TypeScript/ECMAScript标识符。