Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'.

There is a function that retrieves the user role from local storage:

return localStorage.getItem('role');

I am looking to verify if the retrieved item matches one of the predefined string literals mentioned earlier.

Answer №1

To ensure the type of a variable, create a type guard like this:

function checkIfAdmin(arg: string): arg is Admin {
    return arg === 'ADMIN' || arg === 'AGENT';
}

Utilize the type guard in your code as shown below:

let role: string = localStorage.getItem('role');
if (checkIfAdmin(role)) {
    ... now 'role' is recognized as type Admin ...
}

A type guard function asserts the type of its argument with the returned value. By returning true, the compiler understands the specified type.

Though it may involve repeating strings and explicit tests initially, using this approach allows you to write the code once and broaden the scope of type checking effectively.

Answer №2

During the compilation process, types are eliminated which means you cannot rely on them for comparison purposes. Instead, consider utilizing a string-based enum like the following example:

enum UserStatus {
    "ACTIVE",
    "INACTIVE"
}

let status = sessionStorage.getItem("status");

if (status && status in UserStatus) {
    console.log("User status is valid");
};

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

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

Scanning for devices on Ionic 2/3 made simple: How to easily exclude unwanted application and Android directories

I'm currently working on a gallery application that enables users to choose images from their phone and transfer them to a kiosk. Upon loading the application, it searches the entire device for folders containing images and organizes them into an albu ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

Make sure to verify the optional parameter before using it in your code

Is it possible for TypeScript compiler to detect errors in code such as this, with certain tsconfig rules in place? function buildName(firstName: string, lastName?: string) { return firstName + " " + lastName; } I believe that if there is no c ...

Sending an object between two components without a direct parent-child connection

Hello, I have a question similar to the one asked on Stack Overflow regarding passing a value from one Angular 2 component to another without a parent-child relationship. In my scenario, Component1 subscribes to a service that makes a GET request to the ...

Executing Timers in Angular 5 Service

I am working on implementing a property called currentAndLastVehicles in my service that needs to be updated automatically every second. Here is what I have so far: import { Injectable } from '@angular/core'; @Injectable() export class SharedD ...

Encountered an error in production mode with Angular 7: Uncaught ReferenceError - "environment" variable

During development, my application runs smoothly, and ng build --prod --source-map successfully compiles the application. However, when attempting to access it through the browser, an error occurs: app.module.ts:47 Uncaught ReferenceError: env is not defi ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

Extracting information from an Observable in Angular: A comprehensive guide

I am currently working on an Angular application that interacts with a server through RESTful requests, and receives a JSON stream response containing objects of a specific type. The interface for these objects is as follows: export interface Personal { ...

In Angular, set the default value of the first item in the list to be highlighted when the page loads

In my project, there are two key components: 1)contact and 2)display. The contact component is responsible for displaying a list of contacts as shown in the image below: Next to the contact component, I have placed another component called 'display& ...

Surprising fraction of behavior

Looking for some clarification on the types used in this code snippet: interface UserDTO { id: string; email: string; } const input: Partial<UserDTO> = {}; const userDTO: Partial<UserDTO> = { id: "", ...input }; const email = us ...

Trouble arises when attempting to import React JSX project/modules from npm into an AngularJS TypeScript module

In the process of developing a proof-of-concept React framework/library, I aim to create a versatile solution that can be utilized in both React and AngularJS applications. To achieve this goal, I have initiated two separate projects: - sample-react-frame ...

Outside the observable in Angular, there is a vacant array

Within my Angular application, I am facing an issue with the following code snippet located inside a method: let cardArray: string[] = []; this.cardService.getCards().subscribe((cards) => { console.log("1", cards); for (const card of car ...

Definition of Typescript:Named Function Expression (NFE)

In my current project, I am examining the JS code snippet below as part of creating a .d.ts file: BatchBuffer.js var Buffer = function(size) { this.vertices = new ArrayBuffer(size); /** * View on the vertices as a Float32Array for posi ...

Uploading Images to Imgur with Angular 4

As a newcomer to TypeScript, I am faced with the challenge of uploading an image to the Imgur API using Angular. Currently, my approach involves retrieving the file from a file picker using the following code: let eventObj: MSInputMethodContext = <MSIn ...

Implementing unique behaviors based on data types in Typescript

I'm currently working on a React project where I need to showcase different types of articles, which I refer to as "Previews." These articles can be either text-based or contain images/videos. To handle this, I've defined two interfaces (TextPre ...

The validator function in FormArray is missing and causing a TypeError

I seem to be encountering an error specifically when the control is placed within a formArray. The issue arises with a mat-select element used for selecting days of the week, leading to the following error message: What might I be doing incorrectly to tri ...

What is the reason for a high-order generic function to eliminate falsy types from the argument list of the returned function?

Consider this example of a unique Decorator Factory Builder - a builder that constructs Decorator Factories to define metadata for forms: interface FormFieldOptions { name?: string; label?: string; format?: string; } type FormProperties = Record< ...

Combining pixijs with TypeScript in Ionic 2 using npm

To begin, I ran the command npm install -g ionic Followed by ionic start pixiApp blank --v2 Navigated to the pixiApp directory with cd pixiApp Installed necessary dependencies using npm install Added a specific version of pixi.js (4.1.0) with npm install p ...