TS 系列:使用元祖生成联合类型

需求:有这么个需求,我们有两个数组,一个记录扑克牌花色,一个记录扑克牌点数,需要有一个函数,传递两个值,根据传递的值生成扑克牌,需要我们定义参数的类型检查。

思路:肯定不能用 string,这样范围太大了,我们可以使用元祖生成联合类型去检测

const colors = ["♠", "♥", "♣", "♦"] as const;
const values = ['2','3', '4', '5'. '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] as const;

type Values = typeof values[number]
type Colors = typeof colors[number]

function createCard(value: Values, color: Colors) {
  return {
    value,
    color
  }
}

相关推荐

  1. TS 系列使用生成联合类型

    2024-06-08 10:34:05       10 阅读
  2. Python--Tuple

    2024-06-08 10:34:05       17 阅读
  3. TypeScipt 联合类型 | 号的使用

    2024-06-08 10:34:05       10 阅读
  4. uni-app使用uni-ui加ts类型限制

    2024-06-08 10:34:05       33 阅读
  5. 联合类型和交叉类型

    2024-06-08 10:34:05       6 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 10:34:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 10:34:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 10:34:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 10:34:05       20 阅读

热门阅读

  1. 【无标题】

    2024-06-08 10:34:05       8 阅读
  2. CISSP—实现安全治理和原则的策略

    2024-06-08 10:34:05       9 阅读
  3. 小程序中 使用 UDPSocke通讯的流程

    2024-06-08 10:34:05       9 阅读
  4. Oracle如何定位硬解析高的语句?

    2024-06-08 10:34:05       8 阅读
  5. Unity学习要点

    2024-06-08 10:34:05       10 阅读
  6. kali-vulhub(持续更新)

    2024-06-08 10:34:05       8 阅读
  7. 每日一题36:数据分组之科目种类数量

    2024-06-08 10:34:05       10 阅读
  8. kubernetes之安装ingress-nginx(k8s1.19版本之后)

    2024-06-08 10:34:05       12 阅读
  9. azure cli的安装和使用

    2024-06-08 10:34:05       8 阅读