Converting a String variable to a String Literal Type in Typescript: A step-by-step guide

When working with Typescript, imagine I need to call a function that has the following signature-

function foo(param: "TRUE"|"FALSE"|"NONE")

Is there a way to achieve something like this-

var str = runtimeString()
if(str === "TRUE" | str === "FALSE" | str === "NONE")
    foo(str)

Alternatively, is using explicit values the only approach-

var str = runtimeString()
if(str === "TRUE")
    foo("TRUE")
else if(str === "FALSE" )
    foo("FALSE")
else if(str === "NONE")
    foo("NONE")

Answer №1

To start, define a string literal type like so:

type Options = "ONE" | "TWO" | "THREE";

Next, utilize this type when declaring the parameter in the function:

function bar(param: Options)
{
    ...
}

Remember to convert the string into the string literal type before passing it as an argument:

var inputString = getString();
if(inputString === "ONE" || inputString === "TWO" || inputString === "THREE")
    bar(<Options>inputString);

Answer №2

If you are certain that the runtime string corresponds to one of the valid options, you can simply convert your string to the type expected by your function.

type Options = "YES"|"NO"|"MAYBE";

function bar(parameter: Options) {
    return "updated: " + parameter;
}

let input = "MAYBE";
bar(input as Options);

Another method for casting is by explicitly specifying the type like this:

bar(<Options> input);

Keep in mind that by doing this cast, you are overriding the compiler's interpretation of the data within your runtime string. There is a chance that an unexpected value could be passed into your bar function during runtime.

Answer №3

I discovered that creating a type guard is the most effective method.

type NullableBoolean = "TRUE" | "FALSE" | "NONE";
function bar(input: NullableBoolean)
{
    ...
}

function validateNullableBool(value: string): value is NullableBoolean
{
    return value === "TRUE" || value === "FALSE" || value === "NONE"
}

if(validateNullableBool(value)) { bar(value); }

While this approach requires repeating the list of values, it offers better encapsulation compared to Brett's solution.

Answer №4

@JohnDoe provided a solution to address the issue of repetition in the array mentioned earlier by @SimonBergot.

const nullableBooleans = ["TRUE", "FALSE", "NONE"] as const;

type NullableBooleanType = typeof nullableBooleans[number];

const isNullableBooleanValue = (inputValue: unknown): inputValue is NullableBooleanType =>
  nullableBooleans.includes(inputValue as NullableBooleanType);

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

Is there a tidier method for coding this JSX?

Is there a way to optimize these function calls for both onGoClick and onNoGoClicked within the SomeForm component? Or is it fine to keep them as they are? <SomeForm onGoClick={() => { cleanupHere(props) }} o ...

What are the steps for integrating TypeScript code into a Vue component?

https://github.com/bradmartin/nativescript-texttospeech This texttospeech package has TypeScript documentation available. Is there a way to convert this code for use in NS-Vue? import { TNSTextToSpeech, SpeakOptions } from 'nativescript-texttospeec ...

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

Utilizing Angular's async pipe to dynamically customize and assign values to variables

I have a parent component named A with over 20 child components, all of which extend A and are located within <ng-content></ng-content>. Within component A, I am updating the value of the showContent variable in multiple places. The issue aris ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

Utilize Sequelize's cascade feature within your application

I'm currently building a web application using sequelize and typescript. In my database, I have three tables: WfProjectObject, which is connected to WfProject, and WfStep, also linked to WfProject. My goal is to include WfStep when querying WfProject ...

I encountered TS2345 error: The argument type X cannot be assigned to the parameter type Y

Currently, I am delving into the world of Angular 8 as a beginner with this framework. In my attempt to design a new user interface with additional elements, I encountered an unexpected linting error after smoothly adding the first two fields. The error m ...

What is the process for interpreting the status code retrieved from an HTTP Post request?

When sending a POST request to a backend and attempting to read the status code, I encountered the following result: status-code:0 Below are my functions: Service: signIn(uname:string, pass:string): Observable<any> { let headers = new Headers( ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Is there a way to customize the language used for the months and days on the DatePicker

Is there a way to change the language of the DatePicker (months and days) in Material UI? I have attempted to implement localization through both the theme and LocalizationProvider, but neither method seems to work. Here are some resources I have looked a ...

Encountering an error when using Jest and the envalid library to test a React application: process.exit invoked with code "1"

While testing my React/Typescript application with Jest, I encountered an error. I am utilizing the envalid library to manage my environment variables with types and autocompletion: const ENV = cleanEnv(process.env, { | ^ 6 | R ...

Before computing the width, Next.js Swiper slide occupies the entire width

Check out the code snippet below: 'use client'; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; import 'swiper/css/pagination'; export default function Component() { const cards = [{ id: 0 ...

Refreshing Form after Saving in Angular 4

After clicking the Save button, I want to reset the form (addUserForm). I created a modal with a form to input user data. This form serves for both editing existing data and creating new data, with the flag 'Create' or 'Update' differen ...

"Implementing autocomplete feature with initial data in Angular 4 using FormControl

I have incorporated material.angular.io components into my app, particularly autocomplete. I am customizing it to function as a multi-select, but I am encountering an issue with loading initial values: export class CaseActivityTimeEditComponent implements ...

Converting a React Typescript project to Javascript ES5: A step-by-step guide

I have a react typescript project and I need to convert the source code (NOT THE BUILD) to ES3 or ES5 JavaScript. This is because I want to use this code as a component in another React app. Can you suggest which preset and plugins I should use for this t ...

Adding a timestamp to an array in Angular/Typescript services

I've been struggling with adding a timestamp OnInnit to track the time a user visited a page. I want to include the timestamp in an array within my services, but I keep encountering errors and can't seem to figure it out on my own. Any assistance ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

Guide to accessing nested form controls within an array and object in Angular Reactive Forms

As a newcomer to Angular, I am in the process of creating a complex form for a food delivery application that I have been developing. The form I am currently working on is designed to allow me to add a new menu item to a restaurant's menu. In this A ...

What is the best way to show specific links in the navigation bar only when the user is signed in using Angular?

I'm attempting to customize the navigation bar to display "Sign In" and "Sign Up" buttons only when the user is not signed in, and show the message and profile navigation items when the user is signed in. Below is the provided code snippet: Token Se ...