typescript - 是否可以在 Typescript 中提取这种类型?
问题描述
这段代码不起作用,但我想知道是否有办法以基于 svc 参数提供的值的方式键入方法参数?
interface Registry {
"a": {
get: () => {},
},
"b": {
get: () => {},
delete: () => {},
}
}
function callService(svc: keyof Registry, method: keyof Registry[svc]) {} // method type here is wrong
// expected compile errors
callService("a", "get") // ok
callService("b", "get") // ok
callService("b", "delete") // ok
callService("a", "delete") // compile error
解决方案
是的!可以使用泛型
function callService<T extends keyof Registry>( // Define a generic named T for this function.
svc: T, // The generic will take this value.
method: keyof Registry[T] // We can use the generic for other typings.
) {}
推荐阅读
- adsense - 当我添加google autoad脚本进行网站验证时,Hexo自动在脚本标签中添加data-checked-head="true"属性
- javascript - 如何在通过迭代创建 HTML 表时动态设置 id,然后在 onBlur 操作中获取 ID 值?
- pandas - pandas read_csv 中的标记化错误,可以读取我下载的 csv,但不能直接从 url
- javascript - 如何将 URL 转换为可下载的 GeoJSON 文件
- python - 模糊图像的特定点并存储像素值
- winapi - 是否有资源可以找到指定 Windows API 函数的可能错误列表?
- maxima - 使用 Maxima 计算另一个函数的一阶偏导数的函数
- python - 有什么方法可以让 numpy 运行单线程以避免不确定性?
- json - 错误:无法解析 Dockerrun JSON 文件:json:无效使用 ,string struct 标签,试图将未加引号的值解组为 int
- amazon-web-services - 为什么此 Terraform 托管的 AWS Cloudfront 分发会给出错误 403 AccessDenied?