当前位置: 首页 > news >正文

TypeScript - typeof 搭配 as const 技巧总结

这是一种 TypeScript 的高级类型技巧,用于从值推导出类型,实现类型和值的完美同步。

基本语法

const values = ["A", "B", "C"] as const;
type ValueType = typeof values[number];
// ValueType = "A" | "B" | "C"

三个关键组成部分

1. as const - 常量断言

// 没有 as const: string[]
const names1 = ["Alice", "Bob"];// 有 as const: readonly ["Alice", "Bob"]
const names2 = ["Alice", "Bob"] as const;

2. typeof - 类型查询

// 获取值的类型
const arr = [1, 2, 3] as const;
type ArrType = typeof arr; // readonly [1, 2, 3]

3. [number] - 索引访问类型

const values = ["A", "B", "C"] as const;
type ValueType = typeof values[number]; // "A" | "B" | "C"

优势特点

// 只在这里定义一次
const eventNames = ["CREATE", "UPDATE", "DELETE"] as const;
type EventName = typeof eventNames[number];// 类型自动同步:EventName = "CREATE" | "UPDATE" | "DELETE"  

自动同步

// 添加新值
const statuses = ["PENDING", "SUCCESS", "FAILED", "CANCELED"] as const;
type Status = typeof statuses[number];
// Status 自动变为: "PENDING" | "SUCCESS" | "FAILED" | "CANCELED"

运行时可用

// 可以在运行时使用数组
statuses.forEach(status => {console.log(`处理状态: ${status}`);
});// 验证函数
function isValidStatus(status: string): status is Status {return statuses.includes(status as Status);
}

适用场景

1. 固定值集合

// 颜色主题
const themes = ["light", "dark", "system"] as const;
type Theme = typeof themes[number];// 用户角色
const roles = ["admin", "user", "guest"] as const;
type Role = typeof roles[number];

2. 配置选项

const sortOptions = ["name", "date", "price"] as const;
type SortOption = typeof sortOptions[number];

3. API 端点

const apiEndpoints = ["/users", "/posts", "/comments"] as const;
type ApiEndpoint = typeof apiEndpoints[number];

对比其他方案

方案 类型安全 运行时可用 维护性
typeof values[number]
直接联合类型
枚举 ⚠️

最佳实践

推荐使用

// 定义常量数组
const eventNames = ["API:UN_AUTHORIZED", "API:INVAALID", "API:NETWORK_ERROR", "API:SESSION_EXPIRRED"] as const;
type EventName = typeof eventNames[number];
/*** 监听事件* @param eventNme 事件名称* @param listener */
on(eventName: EventName, listener: Function)  {if(eventNames.includes(eventName)) {// 运行时安全this.listeners[eventName].add(listener);}
}

避免使用

// 不需要运行时验证的简单场景
type SimpleStatus = "active" | "inactive";

常见错误

忘记 as const

const colors = ["red", "blue"]; // string[]
type Color = typeof colors[number]; // string

错误的使用场景

// 不适合动态生成的数据
const dynamicValues = fetchDataFromAPI(); // 运行时数据
type DynamicType = typeof dynamicValues[number]; // 可能不是预期的类型

总结

使用时机:当你需要一组固定的值,并且希望在编译时和运行时都能使用这些值。

核心价值:保持类型定义和实际值的完全同步,避免重复和维护负担。

记住口诀:as const 定值,typeof 取型,[number] 得联合,类型值永同步!

http://www.zskr.cn/news/8754.html

相关文章:

  • 图解3:幂等使用场景
  • 推荐一款数据库安全产品:全知科技知形-数据库风险监测系统的价值解析
  • wireshark 进行snmp 协议加密报文解密查看
  • 耳鸣针灸学位
  • 不管不管,就要你的特殊对待(权限)
  • vba里运行miniblink
  • Android Studio无线调试手表App
  • basic - segment tree
  • linux kernel synchronization 1
  • 势能分析揭开一些算法的秘密
  • 企业省钱又安全的5款Linux发行版:从Ubuntu到Pop!_OS全面解析
  • 第六章 数组
  • 0133_解释器模式(Interpreter)
  • trick杂记 例题
  • 网络流 最小割、费用流
  • AdMergeX与小川科技最右App合作案例入选中国信通院“高质量数字化转型典型案例集” - 实践
  • 高效测试的第一步:5个用例设计基础思维模型
  • Python笔记总结
  • 8465:马走日
  • 性能调优之NUMA调优
  • 实用指南:光学神经网络与人工智能应用
  • Zabbix 企业级监控架构实战指南:从搭建、可视化到智能告警
  • U522155 数据生成(小心电脑)
  • 实用指南:OSG中osgFX库
  • 2025.9.20——1橙
  • 用 PHP 和 Tesseract OCR 识别英文数字验证码
  • 凝望深渊时,深渊也凝望着你(黑洞与摇钱树)
  • spring项目部署后为什么会生成 logback-spring.xml记录
  • 202509_NBWS_logbool
  • Kubernetes权威指南-深入理解Pod Service