缩小外部模块提供的接口上的类型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了缩小外部模块提供的接口上的类型相关的知识,希望对你有一定的参考价值。

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

Here's a Playground Link

// 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)

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

答案

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

以上是关于缩小外部模块提供的接口上的类型的主要内容,如果未能解决你的问题,请参考以下文章