When utilizing TS Union Types from an Array, the resulting type will consistently be a

After reading this response, I decided to create some union types from a string[] in order to return a list of valid type values. However, instead of that, the type ends up accepting any string value.

const arrayDays = Array.from(Array(32).keys(), (num) =>
  num.toString().padStart(2, '0'),
)
const listDays = [...arrayDays.splice(1)] as const
type Day = (typeof listDays)[number]

I initially expected that the type Day would be something like

type Days = '01' | '02' .... | '30' | '31'
, but its actual type is string

https://i.stack.imgur.com/iNrPl.png

As a result, when using the Day type in a variable, it accepts any string value.

const day1: Day = '' //does not show an error
const day2: Dat = 'y' //does not show an error

Answer №1

There is a common misunderstanding that types only exist at compile time, leading to the inference of string[] for arrayDays. The compiler cannot determine the type based on runtime values.

To generate a union from your array, you must preserve the information at compile time. Taking inspiration from @jcalz's answer (), I created a Day type that dynamically creates a union similar to your array assigned to arrayDays.

type LessThan<
  N extends number,
  A extends any[] = []
> = N extends A["length"]
  ? A[number]
  : LessThan<N, [...A, A["length"]]>;

type Day<
  F extends number = 0,
  T extends number = 31,
  R extends number = Exclude<T | LessThan<T>, LessThan<F>>
> = R extends LessThan<10> ? `0${R}` : `${R}`;

const day1: Day = "-1"; // invalid
const day2: Day = "3"; // invalid
const day3: Day = "03"; // valid
const day4: Day = "32"; // invalid

Check it out on 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

To run multiple environments with react-native-dotenv in a React Native project using Typescript, only the local environment is activated

Currently, I am facing an issue while trying to initialize my React Native app with TypeScript in three different environments - development, local, and testing. When I attempt to run APP_ENV=testing expo start or APP_ENV=development expo start, it always ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

Is there a way to access and troubleshoot the complete source code within .vue files?

I've been struggling for hours trying to understand why I'm unable to view the full source of my .vue files in the Chrome debugger. When I click on webpack://, I can see the files listed there like they are in my project tree, but when I try to o ...

Discovering the bottom scroll position in an Angular application

I am working on implementing two buttons on an Angular web page that allow the user to quickly scroll to the top and bottom of the page. However, I want to address a scenario where if the user is already at the very top of the page, the "move up" button sh ...

Transforming button click from EventEmitter to RXJS observable

This is the functionality of the component utilizing EventEmitter: import { Component, Output, EventEmitter } from "@angular/core"; @Component({ selector: "app-my-component", template: ` <button (click)="clickEvent($event)& ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

What is the best way to populate an Angular variable in Ionic following a subscription?

Currently, I am in the process of retrieving data from a server and displaying it on an Ionic page. I have successfully fetched the data without any issues and verified it in the console. However, how do I proceed once the server returns the data to me? T ...

Assign a dynamic class to an element within an ngFor iteration

I am working with a template that includes an app-subscriber component being iterated over using *ngFor: <app-subscriber *ngFor="let stream of streams" [stream]="stream" [session]="session" (speakEvents)='onSpeakEvent($event)'> ...

Using MatTableDataSource in a different Angular component

I am working with two components, namely Order and OrderDetail. Within the Order component, I have a MatTableDataSource that gets populated from a service. OrderComponent Prior to the constructor listData: MatTableDataSource<DocumentDetailModel>; ...

Guide to inheriting functions from a parent component in Angular 2

Hello, I am a beginner in the realm of angular2 and would appreciate any assistance in refining my vocabulary and terminology. Currently, I have a class that consists of two directives structured as follows: In parent.component.ts, the Parent component i ...

Just change "this.array[0]..." in the TypeScript code

There is a problem, this.myList[0], this.myList[1], this.myList[2], this.myList[3], // mylist data is 0 ~ 18... this.myList[18] I attempted to solve it by doing the following: for (let i = 0; i < this.myList.length; i++) { this.myList.push( ...

Error: Bootstrap CSS missing from app created with create-react-app-ts

I have a React application that was initially set up using create-react-app-ts. Although I have included bootstrap and react-bootstrap for navigation, the CSS styling from Bootstrap does not seem to be applied properly. The links do not display any styling ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

does not have any exported directive named 'MD_XXX_DIRECTIVES'

I am currently learning Angular2 and I have decided to incorporate angular material into my project. However, I am encountering the following errors: "has no exported member MD_XXX_DIRECTIVES" errors (e.g: MD_SIDENAV_DIRECTIVES,MD_LIST_DIRECTIVES). Her ...

Encountering an issue while trying to integrate custom commands using the addCommand function in WebDriverIO

When using the addCommand function to add a new command, I encountered an error message that states: [ts] Property 'WaitForElementsAmount' does not exist on type 'Client<void>'. Here is an example of the code snippet I used: br ...