Can we limit a specific key to only accept a specific value?

Is it possible to restrict the type of a certain key to a certain value in TypeScript for an object?

For instance, consider the following example:


interface ValueType1 {
    key1: string,
    key2: string,
}

interface ValueType2 {
    key3: number,
    key4: number,
}

type KeyType = 'value1' | 'value2';

const map: {[key in KeyType]: ValueType1 | ValueType2} = {
    'value1': {
        key1: '123',
        key2: '123'
    },
    'value2': {
        key3: 123,
        key4: 123,
    }
}

If we want to ensure that when key = 'value1', the type of Value must be ValueType1 and similarly for value2, is this achievable?

Answer №1

Simply pair the keys with their corresponding types directly. I also suggest utilizing as const satisfies in most scenarios as it can provide more precise and narrow types, which may be advantageous later on:

Playground

type ValueMap = {
  value1: ValueType1,
  value2: ValueType2
}

const map: ValueMap = {
    'value1': {
        key1: '123',
        key2: '123'
    },
    'value2': {
        key3: 123,
        key4: 123,
    }
}

const constMap = {
    'value1': {
        key1: '123',
        key2: '123'
    },
    'value2': {
        key3: 123,
        key4: 123,
    }
} as const satisfies ValueMap

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

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

Displaying only the matched column in an Angular table

I am attempting to display only the matched columns in a table, but I am unsure of how to achieve this. If anyone has any ideas or solutions, please help me out. app.component.ts: columnsOnly = ['name', 'id', 'rank']; ite ...

Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object. Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an ...

Dispatch not invoking Thunk Action - utilizing Typescript

I am currently using React, Redux, Redux-Thunk, and Typescript as a beginner. I have encountered an issue where when I call an action with a thunk, the action is being called (confirmed with a console.log) but the dispatch is not happening. I have connecte ...

Having issues with the updating of React state

Currently, I am in the process of developing a text editor using React alongside Typescript. The component hierarchy is structured as follows: TextEditor -> Blocks -> Block -> ContentEditable. For implementing the ContentEditable feature, I have ...

Can you provide guidance on how to specifically specify the type for the generics in this TypeScript function?

I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below: const obj = { a: 1, b: 2, c: 3 } fun ...

What is the best way to delete previously entered characters in the "confirm password" field after editing the password

Is there a way to automatically remove characters in the confirm password field if characters are removed from the password field? Currently, when characters are entered into the password field, characters can also be entered into the confirm password fiel ...

What could be causing the issue with my customized sorting in the Material-UI Data Grid component?

After integrating Material-UI's Data Grid Component with my API's JSON array, I had to create a RenderCell function to handle text overflow and include a button that directs Users to a different page. Additionally, I utilized the ValueGetter for ...

The attribute 'category' is not recognized on this particular object

While attempting to display a form on Next.js using Formik & typescript, I encountered the following error message: Property 'category' does not exist on type 'IntrinsicAttributes & object & { children?: ReactNode } Here is the code that tr ...

Transform a YAML document into either a JSON blueprint or a TypeScript structure

Currently seeking an efficient tool, preferably in Node JS, that can convert a YAML file from swagger into either a JSON SCHEMA or a typescript interface. The process I have used so far is: YAML->RAML->JSON SCHEMA->TYPESCRIPT interface STEP1: Co ...

Can we handle optional properties that are contingent on a boolean in the type?

My current scenario involves a server response containing a boolean indicating success and optional data or error information. type ServerResponse = { success: boolean; data?: { [key: string]: string }; err?: { code: number, message: string }; } Dea ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...

Error: Unable to access the 'TigerNo' property of an undefined object. Setting tempObj['TigerNo'] to the default TigerNo value from the sports record

I need some help with JavaScript programming. Although I am able to retrieve values in sportsRecord, I am encountering difficulties assigning them to tempObj['TigerNo']. Whenever I try to assign the value, I encounter the following error message ...

Tips for successfully passing arguments in Angular applications

I've encountered an issue while working with mat-autocomplete. My function is not functioning properly when I select an item from the drop-down list. It seems like I need to pass the add() function in my select, but I'm receiving an error stating ...

Is it possible to restrict the parameter of an inherited method in TypeScript?

I have a scenario here where I am extending a node called EventEmitter with my class. The goal is to restrict the events that can be registered. class Foo extends EventEmitter { on(event: 'myEvent', listener: Function): this; emit(event: &ap ...

Exploring the utilization of ngModel within a tag that is selector-based

As a newcomer to Angular 2, I have encountered a challenge with forms that contain multiple text boxes, checkboxes, labels, and drop-downs. When including all these controls in my HTML, the page becomes too long. To address this issue, I would like to crea ...

The error message "Property <property> is not recognized on the type 'jQueryStatic<HTMLElement>'" is indicating an issue with accessing a specific property within the TypeScript codebase that utilizes Angular CLI, NPM,

My Development Environment I am utilizing Angular, Angular CLI, NPM, and Typescript in my web application development. Within one of my components, I require the use of jQuery to initialize a jQuery plugin. In this particular case, the plugin in question ...

What is the best way to extract data from a text file that contains multiple data entries separated by pipes (|) using the fs module?

I'm currently utilizing the node.js fs module to read a text file. One thing that I'm wondering is, does the fs module only support reading text files or can it handle other file formats as well? Now, my primary inquiry is if the text file conta ...