首页 > 解决方案 > 缩小外部模块提供的接口上的类型

问题描述

我有一个外部模块(从 安装@types/some-module)。我想在该模块的命名空间内扩展一个接口,以便该接口上的属性之一比模块给出的更窄。

这是一个游乐场链接

// original.d.ts
namespace SomeNamespace {
  interface SomeInterface {
    id: string;
  }
}

// my.d.ts
declare module 'some-module' {
  namespace SomeNamespace {
    interface SomeInterface {
      id: 'foo' | 'bar'; // what I want to do
    }
  }
}

我可以预见地得到一个错误

Subsequent property declarations must have the same type.  Property
'id' must be of type 'string', but here has type '"foo" | "bar"'. ts(2717)

可能吗?我尝试添加unknownand any,但它不接受它们。

标签: typescript

解决方案


模块扩充允许您添加到接口但不更改现有成员类型。您唯一的选择是扩展接口并将类型断言用于适当的派生接口。


推荐阅读