TypeScript类型能否作为switch()匹配常量?报错排查
TypeScript类型无法在switch case中使用的原因及解决方法
问题核心
你遇到的报错是因为TypeScript的类型仅存在于编译阶段,编译成JavaScript后所有类型定义会被完全擦除,运行时根本不存在CheckoutInvoiceAddressSection这类标识符,自然会抛出ReferenceError。
解决方法
要同时满足编译时类型检查和运行时变量使用的需求,有两种常用方案:
方案1:常量+typeof生成类型
修改checkoutTypes.ts,先定义运行时可用的字符串常量,再基于常量生成对应类型:
// checkoutTypes.ts // 导出运行时可用的常量 export const CheckoutInvoiceAddressSection = "InvoiceAddress"; export const CheckoutDeliveryAddressSection = "DeliveryAddress"; export const CheckoutDeliveryAndReviewSection = "DeliveryAndReview"; // 基于常量生成编译时类型 export type CheckoutInvoiceAddressSection = typeof CheckoutInvoiceAddressSection; export type CheckoutDeliveryAddressSection = typeof CheckoutDeliveryAddressSection; export type CheckoutDeliveryAndReviewSection = typeof CheckoutDeliveryAndReviewSection; export type CheckoutSection = CheckoutInvoiceAddressSection | CheckoutDeliveryAddressSection | CheckoutDeliveryAndReviewSection;
在使用文件中,同时导入常量和类型(注意类型导入要加type关键字):
import { CheckoutInvoiceAddressSection, CheckoutDeliveryAddressSection, CheckoutDeliveryAndReviewSection, type CheckoutSection } from "~/types/checkoutTypes"; interface Props { identifier: CheckoutSection, } const props = defineProps<Props>(); const isSectionCompleted = computed(() => { switch (props.identifier) { case CheckoutInvoiceAddressSection: return checkoutStore.getActiveSection !== CheckoutInvoiceAddressSection; case CheckoutDeliveryAddressSection: return checkoutStore.getActiveSection === CheckoutDeliveryAndReviewSection; // 增加default分支避免TS提示"函数缺少返回值"的错误 default: return false; } });
方案2:使用枚举(Enum)
直接用TypeScript枚举来统一管理类型和运行时值:
// checkoutTypes.ts export enum CheckoutSection { InvoiceAddress = "InvoiceAddress", DeliveryAddress = "DeliveryAddress", DeliveryAndReview = "DeliveryAndReview" }
使用时直接导入枚举即可:
import { CheckoutSection } from "~/types/checkoutTypes"; interface Props { identifier: CheckoutSection, } const props = defineProps<Props>(); const isSectionCompleted = computed(() => { switch (props.identifier) { case CheckoutSection.InvoiceAddress: return checkoutStore.getActiveSection !== CheckoutSection.InvoiceAddress; case CheckoutSection.DeliveryAddress: return checkoutStore.getActiveSection === CheckoutSection.DeliveryAndReview; default: return false; } });
注意事项
- 两种方案都能避免硬编码字符串,减少拼写错误
- 务必添加
default分支,避免TypeScript提示函数缺少返回值的编译错误
内容的提问来源于stack exchange,提问作者xTheWolf
相关产品推荐
相关产品推荐

