在 switch() 中使用类型作为常量?

问题描述 投票:0回答:1

我在

checkoutTypes.ts
文件中有一些类型,如下所示:

export type CheckoutInvoiceAddressSection = "InvoiceAddress";
export type CheckoutDeliveryAddressSection = "DeliveryAddress";
export type CheckoutDeliveryAndReviewSection = "DeliveryAndReview";

export type CheckoutSection = CheckoutInvoiceAddressSection | CheckoutDeliveryAddressSection | CheckoutDeliveryAndReviewSection;

在不同文件中的函数中,我想在

switch()
语句中使用它们进行大小写匹配:

import type { CheckoutInvoiceAddressSection, CheckoutDeliveryAddressSection, CheckoutDeliveryAndReviewSection, 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;
  }
});

但是,我收到以下错误:

ReferenceError: CheckoutInvoiceAddressSection is not defined
。在
case CheckoutInvoiceAddressSection
线上。 类型定义不适合用于与变量进行比较,还是我遗漏了其他内容?

typescript vue.js
1个回答
0
投票

正如 @jonrsharpe 已经提到的,TypeScript 在运行时不存在。您可以将值导出为常量,并从中获取您想要的类型,如下所示:

export const CheckoutInvoiceAddressSection = "InvoiceAddress";
export const CheckoutDeliveryAddressSection = "DeliveryAddress";
export const CheckoutDeliveryAndReviewSection = "DeliveryAndReview";

export type CheckoutInvoiceAddressSectionType = typeof CheckoutInvoiceAddressSection;
export type CheckoutDeliveryAddressSectionType = typeof CheckoutDeliveryAddressSection ;
export type CheckoutDeliveryAndReviewSectionType = typeof CheckoutDeliveryAndReviewSection ;

export type CheckoutSectionType = CheckoutInvoiceAddressSectionType | CheckoutDeliveryAddressSectionType | CheckoutDeliveryAndReviewSectionType;

现在我们可以访问值和类型了

import { CheckoutInvoiceAddressSection, CheckoutDeliveryAddressSection, CheckoutDeliveryAndReviewSection, CheckoutSectionType } from "~/types/checkoutTypes";

interface Props {
  identifier: CheckoutSectionType,
}
const props = defineProps<Props>();

const isSectionCompleted = computed(() => {
  switch (props.identifier) {
    case CheckoutInvoiceAddressSection:
      return checkoutStore.getActiveSection !== CheckoutInvoiceAddressSection;
    case CheckoutDeliveryAddressSection:
      return checkoutStore.getActiveSection === CheckoutDeliveryAndReviewSection;
  }
});

您可能还对 enums 感兴趣。

const enum
被转换为常量值,所以你实际上可以做这样的事情:

const enum EDirection {
  Up,
  Down,
  Left,
  Right,
}

// Using the enum as a parameter
function walk(dir: EDirection) {}

walk(EDirection.Left);
© www.soinside.com 2019 - 2024. All rights reserved.