Is it possible to utilize types as constants in a switch statement?

In my file called checkoutTypes.ts, I have defined some checkout types like this:

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

export type CheckoutSection = CheckoutInvoiceAddressSection | CheckoutDeliveryAddressSection | CheckoutDeliveryAndReviewSection;

In a function within a different file, I intend to utilize these types for matching cases in a switch() statement:

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;
  }
});

However, an error is appearing:

ReferenceError: CheckoutInvoiceAddressSection is not defined
. on the line with
case CheckoutInvoiceAddressSection
. Can type definitions not be used for comparison with a variable, or am I overlooking something else?

Answer №1

In addition to @jonrsharpe's point, it is important to note that TypeScript does not persist at runtime. One approach you can take is to export your values as constants and extract the desired types from them like so:

export const CheckoutInvoiceAddress = "InvoiceAddress";
export const CheckoutDeliveryAddress = "DeliveryAddress";
export const CheckoutDeliveryAndReview = "DeliveryAndReview";

export type CheckoutInvoiceAddressType = typeof CheckoutInvoiceAddress;
export type CheckoutDeliveryAddressType = typeof CheckoutDeliveryAddress;
export type CheckoutDeliveryAndReviewType = typeof CheckoutDeliveryAndReview;

export type CheckoutSectionType = CheckoutInvoiceAddressType | CheckoutDeliveryAddressType | CheckoutDeliveryAndReviewType;

This enables access to both the values and the associated types.

import { CheckoutInvoiceAddress, CheckoutDeliveryAddress, CheckoutDeliveryAndReview, CheckoutSectionType } from "~/types/checkoutTypes";

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

const isSectionComplete = computed(() => {
  switch (props.identifier) {
    case CheckoutInvoiceAddress:
      return checkoutStore.getActiveSection !== CheckoutInvoiceAddress;
    case CheckoutDeliveryAddress:
      return checkoutStore.getActiveSection === CheckoutDeliveryAndReview;
  }
});

If you are interested, you may want to explore enums. The use of a 'const enum' is transpired into constant values, allowing for functionalities such as:

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

// Utilizing the enum in a function parameter
function move(direction: EDirection) {}

move(EDirection.Left);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the dropdown menu title dynamically based on the selection made in Angular

My Angular web-application has a dropdown menu that looks like this: <div class="btn-group" dropdown> <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN <span class="caret"></span>&l ...

Endless cycle of socksjs in vue.js

I am currently utilizing vue.js in conjunction with a flask server. The vue.js dev environment on port 8080 forwards axios queries to port 80, where my Python flask server is constantly waiting for web service calls. Below is the content of my vue.config. ...

Lexicaljs utilizes debounce to receive editor state JSON and text content in a React project

What I Need I am looking to retrieve the editor state in JSON format, along with the text content of the editor. Moreover, I prefer to receive these values in a debounced manner, as described here. The reason I want to obtain the values in a debounced wa ...

Using Vue.js to set and retrieve changes on a range slider with v-model

Currently, I am in the process of adding a slider feature to my web form, allowing users to input their desired rating for a specific item. https://i.sstatic.net/e2a6L.png Utilizing Vue.js for this task, I am seeking guidance on how to properly configure ...

Guide to configuring the overflow-y property for individual cells or rows in a Bootstrap-Vue table

Hello there, I am currently using Bootstrap-vue to display data that has been queried from a database. My goal is to have it displayed with an overflow-y style similar to this image. If you know how to achieve this effect, please share your solution. Here ...

What is the process for integrating vis.js into a Vue.js application?

Can someone help me with installing and utilizing Vis.js in Vue.js? I attempted to follow the instructions provided, but received an error message stating Viz is not a constructor https://github.com/mdaines/viz.js/wiki/Usage ...

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

When it comes to rendering components in React using multiple ternary `if-else` statements, the question arises: How can I properly "end" or "close" the ternary statement?

I have developed a straightforward component that displays a colored tag on my HTML: import React, {Component} from 'react'; import "./styles.scss"; interface ColorTagProps { tagType?: string; tagText?: string; } /** * Rende ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Tips for implementing a condition such as "greater than or equal to" in the filtering search feature in Vue.js

Hey everyone, I need help with building a real estate application. I want to add a condition in the Bedrooms filter function where it filters properties greater than or equal to a selected number. For example, if I select 2 on the Bedroom list, I want the ...

Unpacking objects in Typescript

I am facing an issue with the following code. I'm not sure what is causing the error or how to fix it. The specific error message is: Type 'CookieSessionObject | null | undefined' is not assignable to type '{ token: string; refreshToken ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...

Creating a Personalized Color Palette Naming System with Material UI in TypeScript

I have been working on incorporating a custom color palette into my material ui theme. Following the guidance provided in the Material UI documentation available here Material UI Docs, I am trying to implement this feature. Here is an excerpt from my cod ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

Displaying or concealing list elements in Angular 6

I am working on a simple Angular app that displays a list of items. I want the behavior to be such that when the first item in the list is clicked, its description (card) should be displayed. And, if the second item is clicked and its description is displa ...

Problem with loading image from local path in Angular 7

I'm having trouble loading images from a local path in my project. The images are not rendering, but they do load from the internet. Can someone please help me figure out how to load images from a local path? I have already created a folder for the im ...

Angular HttpClient mapping causes the removal of getters from the target object

Utilizing the HttpClient to fetch Json data from an API, I am utilizing the autoMapping feature of the HttpClient to map the json response to a specified object in this manner: this.httpClient.post<Person>(url, body, { headers: headers, params: http ...

Link to the Vue Bootstrap Toast Message

I have integrated vue-bootstrap-toasts (demo) into my website to display Toasts. However, I am facing an issue with adding a link to the toast that should redirect to another page. this.$toast.success('Test is created', { href: "www.googl ...

Error encountered with laravel and vue.js: Module not found

After attempting to install Vue in Laravel using the specified commands, I encountered a new error that I have not seen before: Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' Require stack: - C:\wamp64\w ...

What are the best ways to integrate markdown into my Vue.js projects?

Is there a way to utilize markdown within the context of vue.js instead of regular HTML paragraphs? ...