typescript - 缩小外部模块提供的接口上的类型
问题描述
我有一个外部模块(从 安装@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)
可能吗?我尝试添加unknown
and any
,但它不接受它们。
解决方案
模块扩充允许您添加到接口但不更改现有成员类型。您唯一的选择是扩展接口并将类型断言用于适当的派生接口。
推荐阅读
- java - 使用 BufferedReader 将文件内容存储在 Integer 的 ArrayList 中
- qt - 如何知道qml中的lib版本
- java - 在 JUnit 4 的“gradle test”开始时运行初始化程序
- javascript - JSPDF autotable - 打破大表
- php - PDO 是否仍在为 MySQL 模拟准备好的语句?
- asp.net-mvc - 在视图 MVC 5 上渲染时隐藏输入不起作用
- c++ - 为什么带有type参数的operator()可以在result_of的上下文中应用于type?
- reactjs - 扩展类和更改属性
- python - 如何在 django 项目中调用命令?
- c# - 服务器上传代码按时比较问题