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

Narrowing a type on an interface provided by an external module

提问人:Madara's Ghost 提问时间:4/14/2019 更新时间:4/22/2020 访问量:160

问:

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

这是一个 Playground 链接

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

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

打字稿

评论


答:

1赞 Titian Cernicova-Dragomir 4/14/2019 #1

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

-1赞 Squirrelkiller 4/22/2020 #2

不幸的是,'foo'|'bar' 不是字符串类型,union 类型更像是 TypeScript 中的枚举。

最好的主意是将 id 限制为 'foo'|' 的工厂方法酒吧'。
不幸的是,我没有想法可以帮助您自动完成这些值。