typescript - 如何返回从 TS 中的数组中提取的相应(按索引)窄类型的记录
问题描述
我的情况可以用下面的例子来概括:
interface Config {
readonly key: string,
readonly config: number,
}
// narrow typed array
const arr = [{key:"hi", config:34}, {key:"hello", config:75}] as const;
function fn<T extends ReadonlyArray<Config>>(configs: T) {
type ks = T[number]['key'];
type cs = T[number]['config'];
return {} as {
[K in ks]: cs
}
}
const res = fn(arr);
我需要{hi:34, hello:75}
作为返回类型,但目前的类型res
是{hi:34|75, hello:34|75}
. 我不知道我应该执行哪些其他类型的操作cs
来获得我需要的东西,也不知道 usingcs
是否是正确的方法。
解决方案
您可以用户提取以获取与当前键对应的元组项的联合中的项:
interface Config {
readonly key: string,
readonly config: number,
}
// narrow typed array
const arr = [{key:"hi", config:34}, {key:"hello", config:75}] as const;
function fn<T extends ReadonlyArray<Config>>(configs: T) {
type ks = T[number]['key'];
type cs = T[number];
return {} as {
[K in ks]: Extract<cs, {key: K}>['config']
}
}
const res = fn(arr); // { hi: 34; hello: 75; }
推荐阅读
- excel - 如何计算 Excel VBA 代码中的错误?
- c++ - 继承ostringstream时的歧义
- mysql - 单个查询:获取 12 个月的评级,但计算所有
- php - PHP:使用 GML 标签解析 XML 文件
- javascript - 如何知道孩子在深度嵌套的对象中处于什么级别?
- amazon-web-services - AWS SSO SCIM 访问令牌到期通知
- c++ - -Wunused-but-set-variable 在我使用“auto”时发出,而不是在我使用相应类型而不是“auto”时发出
- python - 具有不同概率的向量化 np.random.choice
- azure - 从新资源访问现有资源信息
- python - Python 仅在数据框中包含数字列