gpt4 book ai didi

typescript - TypeScript 中具有排列的动态类型

转载 作者:行者123 更新时间:2023-12-05 04:21:20 24 4
gpt4 key购买 nike

我想创建不包括重复项的动态类型。这是我现在拥有的:

type Currency = 'CAD' | 'USD' | 'EUR';
type CurrencyQuote = `${Currency}x${Currency}`; // returns: "CADxUSD" | "USDxCAD" | "CADxCAD" | "CADxEUR" | "USDxUSD" | "USDxEUR" | "EURxCAD" | "EURxUSD" | "EURxEUR"

我如何排除重复的那些,例如 USD|USDCAD|CADEUR|EUR

谢谢

最佳答案

我们可以使用 mapped type它映射了 Currency 中的元素并构造由当前元素 K 组成的模板字符串文字Exclude<Currency, K> .

由于映射类型返回一个以货币作为属性的对象,我们需要用 Currency 索引这个类型获取所有键类型的并集。

type CurrencyQuote = {
[K in Currency]: `${K}x${Exclude<Currency, K>}`
}[Currency]

// type CurrencyQuote =
// | "CADxUSD"
// | "CADxEUR"
// | "USDxCAD"
// | "USDxEUR"
// | "EURxCAD"
// | "EURxUSD"

您可能需要一个可重用的实用程序类型来执行此操作。

type ConcatWithoutDupes<T extends string> = {
[K in T]: `${K}x${Exclude<T, K>}`
}[T]

type CurrencyQuote = ConcatWithoutDupes<Currency>

Playground

关于typescript - TypeScript 中具有排列的动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74249406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com