You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中将已声明类型作为值使用?

TypeScript类型作为值使用的解决方案

TypeScript中的type属于编译时类型,编译为JavaScript后会被彻底移除,因此直接像引用值一样调用CardType会触发CardType is not defined的错误。要实现“类型和值复用”,可以用以下两种方式:

方式一:基于常量生成类型(推荐)

先定义可作为值使用的常量,再通过typeof推导对应的类型,这种方式编译后无额外代码开销:

// 定义可直接使用的常量
const CardType = 'InformationCard' as const;
// 基于常量自动推导类型
type CardType = typeof CardType;

使用示例:

// 当作值使用
console.log(CardType); // 输出 'InformationCard'

// 当作类型使用
const myCard: CardType = 'InformationCard'; // 类型合法
// const myCard: CardType = 'OtherCard'; // 类型校验报错

方式二:使用枚举

枚举编译后会生成对应的JavaScript对象,能同时提供类型约束和值访问,但会增加少量代码体积:

enum CardType {
  InformationCard = 'InformationCard'
}

// 提取枚举成员作为类型
type CardType = CardType.InformationCard;

使用示例:

// 当作值使用
console.log(CardType.InformationCard); // 输出 'InformationCard'

// 当作类型使用
const myCard: CardType = CardType.InformationCard; // 类型合法

内容的提问来源于stack exchange,提问作者Ali Bahaari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:27:07