
假设您有一个 for in 循环,突然意识到您的变量类型是字符串而不是字符串文字联合类型。因此,当您使用 tsc 编译应用程序时,您会遇到这个丑陋的错误,并且令人烦恼的是您最喜欢的 ide 很可能会在其冲刺的顶部尖叫:
element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ user: number; nice: number; sys: number; idle: number; irq: number; }'.
no index signature with a parameter of type 'string' was found on type '{ user: number; nice: number; sys: number; idle: number; irq: number; }'.ts(7053)
[!注意] 只是为了向您展示它是如何完成的,我正在使用 os.cpus。在那里我尝试循环 cpu.times 这是一个对象。您可以在这里找到更多信息。 所以这是有问题的代码: import { cpus } from 'os'; const logicalcoresinfo = cpus(); for (const logicalcoreinfo of logicalcoresinfo) { let total = 0; for (const type in logicalcoreinfo.times) { total += logicalcoreinfo.times[type]; // darn it, ts is upset! } }
所以让我们开始吧,对于第一部分,我们需要为自己创建一个自定义实用程序类型,这是我们最终的实用程序类型的样子:
type nestedkeysof<t, k extends propertykey> = t extends object
? {
[tkey in keyof t]-?:
| (tkey extends k ? keyof t[tkey] : never)
| nestedkeysof<t[tkey], k>;
}[keyof t]
: never;
让我们来分解一下:
[t 键中的 t 键]-?是一个“映射类型”,它在这里特别有用,因为我们不知道传递给该实用程序类型的对象内的键的名称。在这里,您将逻辑核心信息传递给它或任何其他对象,然后它迭代键以从中创建一个新类型。
还有-?是否可以删除可选性,以便我们拥有所有键的字符串文字联合类型。换句话说, { keyname?: string } 将被视为 { keyname: string }.
(tkey extends k ? keyof t[tkey] : never) 检查迭代中的当前键是否与传递的键 (k) 匹配,如果是,则将其中的所有键提取为字符串文字联合类型并归还它。否则它什么也不返回。
然后,如果步骤 3 没有结果,它将递归地在 t[tkey] 上应用此实用程序类型,这样我们的实用程序函数也适用于嵌套对象。这通常称为“递归条件类型”。
最后我们要求它取映射类型生成的所有类型的并集。简而言之,我们正在展平嵌套结构。
现在是时候使用它了:
interface Person {
name: string;
address: {
street: string;
city: string;
};
}
type KeysOfAddress = NestedKeysOf<Person, 'address'>; // "street" | "city"
// Or in our original example:
type CpuTimesKeys = NestedKeysOf<typeof logicalCoreInfo, 'times'>;
// ...
total += logicalCoreInfo.times[type as CpuTimesKeys];
// ...
以上就是递归条件类型的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号