Assigning values based on conditions for unions of types

I'm currently exploring typescript and facing a challenge with dynamically assigning values to a union type:

type Labs = (name === 'dakota') ? 'fruit' | 'veg' : 'plow' | 'field' | 'till';

An error keeps popping up stating that "name refers to a value but is being used as a type".

To clarify, my goal is to restrict the valid values of type Lab:

type Labs = 'fruit' | 'veg'
// if name === 'dakota', otherwise:
type Labs = 'plow' | 'field' | 'till'

I've attempted using a function that will return the correct type:

function getLabType<Type>(arg: string): Type {
  if (arg === 'dakota') {
    type A = 'fruit' | 'veg';
    return A
  }
  type B = 'plow' | 'field' | 'till'
  return B
}

type Lab = getLabType('dakota')

However, I am encountering a similar warning about A and B only referring to types but being used as values.

If you have any insights on how I can conditionally set values for a union type, I would greatly appreciate your help.

Answer №1

You have the ability to accomplish this using generics and function overloads:

function getLabType<T extends string>(arg: T): T extends 'dakota' ? 'fruit' | 'veg' : 'plow' | 'field' | 'till'
function getLabType(arg: string): string {
    if (arg === 'dakota') {
        return 'fruit';
    }
    return 'field';
}

const fruitOrVeg = getLabType('dakota');
const plowFieldOrTill = getLabType('other');

TypeScript playground

If you solely require a type (no JavaScript) then proceed as follows:

type Labs<T> = T extends 'dakota' ? 'fruit' | 'veg' : 'plow' | 'field' | 'till';

Subsequently utilize it like Labs<typeof name> or any other identifier.

TypeScript playground

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

Guide on creating a generic type that depends on the arguments provided, specifically a union type

I am dealing with the following similar types: class ActionFoo { action: 'foo'; foo: string; } class ActionBar { action: 'bar'; bar: number; } In addition, I have some handler functions for each type of defined "action", such a ...

Steps to eliminate the typescript template from create-react-app

Initially, I decided to incorporate TypeScript into my React project, which led me to run the command npx create-react-app my-app --template typescript. However, now I'm looking for a way to revert back and remove TypeScript from my setup. Is there a ...

connect the validation of forms to different components

I am currently working on components to facilitate the user addition process. Below is an example of my form component: createForm(): void { this.courseAddForm = this.formBuilder.group({ name: ['', [ Validators.required, ...

Adding a custom role in Angular TypeScript in Microsoft AppInsights is a straightforward process that can provide valuable

I have an angular project where I am looking to incorporate AppInsight with custom telemetry (role). The project is built in Angular using TypeScript, and I successfully integrated appinsights by following this tutorial. However, when attempting to add cus ...

Encountered React error: Cannot assign type 'string | string[]' to type 'string[]'

I am brand new to React but have a good grasp on vanilla JS, and I've been following a YouTube tutorial. The tutorial took a different approach in this section which is why I need some guidance. Essentially, I'm defining an 'interface ListP ...

What is the significance of "&" and "|" following a type declaration in TypeScript?

Recently, I came across a TypeScript code snippet that looked something like this: type Point = PartialPointX & { y: number; }; It got me thinking about the differences between '&' and '|' in TypeScript. While I know that '& ...

In Typescript, you can easily group a string into sections that consist of digits like 345-67, along with text containing a

I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challeng ...

What is the method for utilizing OR statements in Playwright assert?

How can I verify whether the text content is either one or two using Playwright? await expect(this.header).toHaveText('one').or('two') Is there a way to achieve this functionality in Playwright? Additionally, can this feature be inco ...

Using the Yammer REST API to post messages.json with a line break

I'm having trouble adding line breaks to my posts on Yammer through the REST API. While I can include line breaks when posting directly on Yammer, I can't seem to achieve the same result programmatically. It appears that Yammer may be escaping th ...

Having trouble with Angular 2 when submitting a form

Whenever I try to submit a form with two input fields and one select list, the submitted value for the select list is always 0. I am unsure where I am making a mistake. When I post this form to an API, all values are correct except for the select list valu ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

React and TypeScript warns about possible undefined object

certificate?: any; <S.Contents>{certificate[0]}</S.Contents> <S.Contents>{certificate[1]}</S.Contents> <S.Contents>{certificate[3]}</S.Contents> If I set the type of props to `any` and use it as an index of an array, e ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

Step-by-step guide on navigating back in Angular 12 without triggering a page refresh

As an illustration, consider a scenario where I input values into a table and move to the next page. Upon returning to the page, I expect the entered values to still be present. I attempted to achieve this using this._location.back(), but instead of disp ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

Tips for setting up the configuration of @typescript-eslint guidelines

I am in the process of transitioning to @typescript-eslint but I am finding the documentation to be quite inadequate. One specific issue I am facing is the errors like the following: Line 58: Expected a semicolon @typescript-eslint/member-del ...

The rendering of ReactJS context-api is not working as expected after receiving the data

This is a unique site built on next.js. To ensure both my Navbar component and cart page have access to the cart's content, I created a context for them. However, when trying to render the page, I encounter the following error: Unhandled Runtime Erro ...

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 ...