How can I use Typescript to define a function that accepts a particular string as an argument and returns another specific string?

I've been working on this code snippet:

const Locales = {
  en_gb: 'en-gb',
  en_us: 'en-us',
} as const

type ApiLocales = typeof Locales[keyof typeof Locales]
type DatabaseLocales = keyof typeof Locales

function databaseLanguageCodeFromString(languageString: ApiLocales): DatabaseLocales[ApiLocales] {
  return {
    'en-gb': 'en_gb',
    'en-us': 'en_us',
  }[languageString]
}

But I'm unsure about its functionality and whether it will actually work at runtime. It's crucial for my database to only accept Enum-compliant values, so this could be a potential issue. I would like to catch any errors in my code before they impact the database.

Answer №1

Is it compatible during runtime?

When it comes to TypeScript, the types are not accessible during runtime. If you need to verify the types of data being transmitted or received through a network request or a similar interface, there are runtime type-checking libraries available for this purpose. Some popular options include Zod and io-ts.

Answer №2

The code will function during runtime, but there are some discrepancies in your types.

Here is the revised code:

const Locales = {
  en_gb: 'en-gb',
  en_us: 'en-us',
} as const;

// Utilizing a type to reverse the record type
type Reverser<T extends Record<PropertyKey, PropertyKey>> = { [P in keyof T as T[P]]: P; }

type ApiLocales = typeof Locales[keyof typeof Locales]
type DatabaseLocales = Reverser<typeof Locales>

function databaseLanguageCodeFromString(languageString: ApiLocales): DatabaseLocales[ApiLocales] {
  return ({
    'en-gb': 'en_gb',
    'en-us': 'en_us',
  } as const)[languageString]
}

By simply reversing the Locales for DatabaseLocales, the issue is resolved. Also, remember to specify as const for the object in the function.

Access 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

What is the procedure for cancelling a file upload in the FileUpload component of PrimeNG?

1. Issue Overview Looking to terminate file upload in PrimeNG's FileUpload component when certain filename patterns are detected. Using Angular 6.0.7 and PrimeNG 6.0.2. 2. Initial Strategy 2.1. HTML Code <p-fileUpload #fileUploader name="file" ...

How can you annotate and inherit a class method that returns an array of itself?

In the following example, I present a simplistic representation of code that may not align with standard HTML or front-end conventions. Please excuse any confusion this may cause. TL, DR I am facing challenges in specifying a return type for a method tha ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

Variations in comparing tuple types in TypeScript

Exploring the TypeScript Challenge, there is a particular problem known as IsNever. The task at hand is to create a type called IsNever that takes input of type T. If the resolved type equates to never, the output should be true; otherwise, it should be fa ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

How can I modify the appearance of folders in FileSystemProvider?

I have created an extension for vscode that includes a virtual filesystem with fake directories and files. While the extension is functioning properly, I am facing some challenges in customizing certain aspects due to lack of documentation. 1) I need to u ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

Why styled-components namespace problem in React Rollup build?

I designed a "UI Library" to be utilized in various projects using ReactJS + TypeScript + styled-components and Rollup. However, I am currently encountering issues with conflicting classNames. I am aware that styled-components offers a plugin for creating ...

A custom Typescript type for immutable values within an object

I am struggling with finding the right data type for my function, where I need to work with static types. I have experimented with Type, interface, class, Record, and others, but none seem to fit perfectly. GEOLOCATIONS is a constant record that maps cou ...

Issues with Firebase Cloud Messaging functionality in Angular 10 when in production mode

Error: Issue: The default service worker registration has failed. ServiceWorker script at https://xxxxxx/firebase-messaging-sw.js for scope https://xxxxxxxx/firebase-cloud-messaging-push-scope encountered an error during installation. (messaging/failed-ser ...

The data type 'A | B' cannot be assigned to type 'A & B'

What could be causing the compilation error in this code? type A = { n: number } type B = { s: string } type Thing = { a: A b: B } function update(obj: Thing, path: keyof Thing) { obj[path] = obj[path] } It seems like both sides of the assignment sh ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Removing the AM and PM from OwlDateTime in Angular is simple since the time format is already in 24-hour time

Using OwlDateTime in a 24-hour format: <div *ngIf="isSchedule" class="form-inline"> <label style='margin-right:5px ;margin-left:210px'> Date Time: <input [owlDateTimeTrigger]="dt" [owlDateTime]="dt" class="form-control" placeh ...

Unable to initiate ngModelChange event during deep cloning of value

I've been struggling to calculate the sum of row values, with no success. My suspicion is that the issue lies in how I am deep cloning the row values array when creating the row. const gblRowVal1 = new GridRowValues(1, this.color, this.headList ...

Eslint is unable to locate file paths when it comes to Solid.js tsx extensions

Whenever I attempt to import TSX components (without the extension), Eslint raises an error stating that it's unable to resolve the path: https://i.sstatic.net/NiJyU.png However, if I add the TSX extension, it then prompts me to remove it: https:// ...

What is the process for defining a type that retrieves all functions from a TypeScript class?

Imagine having a class called Foo class Foo { bar(){ // do something } baz() { // do something } } How can you define a type ExtractMethods that takes a class and returns an interface or type containing the class methods? For example: t ...