Limiting an interface to certain keys within a combination of types

I have a list of specific keys that are allowed in a union type:

type AllowedKeys = "a" | "b";

Now, I am defining an interface and I want to make sure that only the allowed keys can be used in this interface:

interface Interface {
  a: Something; // This is acceptable
  c: SomethingElse; // I want this to result in an error
}

How can I ensure that the interface aligns with the allowed keys?

Answer №1

Using an interface will not work for this scenario

The reason is that TypeScript interfaces are inherently open-ended, allowing for the flexibility required to mimic JavaScript's extensibility.

This means you can continually add new properties to an interface.

Instead, consider using

type AllowedTypes =  {
    "a" : string;
    "b": number ;
}

type AllowedKeys = keyof AllowedTypes;

Answer №2

When it comes to defining types, you have the option to use interfaces or types in TypeScript. If you opt for using types, you can achieve the following:

type AllowedKeys = "a" | "b";

export type TestType = {
    [key in AllowedKeys]: Something;
};

This approach ensures that both keys specified in AllowedKeys are utilized within your defined type. An example scenario would be as follows:

An error will be raised with this code snippet:

const a: TestType = {
    a: 'asd',
    b: 'asd',
    c: 'asd'
}

On the other hand, the following code is acceptable:

const a: TestType = {
    a: 'asd',
    b: 'asd',
}

However, even this will trigger an error:

const a: TestType = {
    a: 'asd',
}

If utilizing all allowed keys is not necessary, you can denote optional keys by adding ? to your type declaration:

export type TestType = {
    [key in AllowedKeys]?: string;
};

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

Issue: The 'draggable' property is not found on the 'JQuery<HTMLElement>' type

When using Angular 2 and Typescript in conjunction with JQuery and JQueryUI, I encountered the following error: Property 'draggable' does not exist on type 'JQuery<HTMLElement>' I am aware that .draggable() is a function that rel ...

Can you explain the concept of widening in relation to function return types in TypeScript?

Recently, I've observed an interesting behavior in TypeScript. interface Foo { x: () => { x: 'hello' }; } const a: Foo = { x: () => { return { x: 'hello', excess: 3, // no error } }, } I came acro ...

Developing a TypeScript frontend library

I am currently in the process of creating a frontend library consisting of React components and CSS/SCSS. Specifically, I am looking for: To build a single CommonJS .js file and .css file. To exclude external libraries (e.g. React) from the .js output. ...

Numeric String Expected Error Encountered in NestJS DTO Validation

While working on my NestJS application, I encountered a validation error when making a request to the http://localhost:3000/users/authstatus endpoint. The error message displayed was: { "message": "Validation failed (numeric string is ex ...

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

An unexpected loop is generated by Angular2's ngFor

Attempting to implement ngFor in Angular 2 rc-1, here is an example: @Component({ selector: 'myList', template: `<h2>Menu</h2> {{title}} <ul> <li *ngFor="let menu o ...

Why am I encountering a 504 server error in the live environment while attempting to establish a connection with the database?

I feel like I'm losing my sanity. I've attempted this multiple times by now. Currently, I'm working on setting up an authentication flow using a project tutorial I stumbled upon on YouTube. The goal is to establish the flow with Next.js and ...

What is causing the error message "Module '@reduxjs/toolkit' or its type declarations are not found" to appear?

Although I have a good understanding of React-Redux, I decided to delve into TypeScript for further practice. Following the recommended approach from the react-redux team, I created a new project using the TS template: "npx degit reduxjs/redux-templa ...

The limitations of Typescript types influence the program's behavior

As a newcomer to the Typescript environment, I am currently developing a test application to familiarize myself with it. However, I have encountered an issue regarding type restrictions that seems to be not working as expected. In my class, I have defined ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

Utilizing several data sources within a single mat-table

Hello, I require assistance with a task. I am trying to display multiple mat-tables with different data sources in my component.ts file Groups(){ this.apiSvc.Cards().subscribe((rsp: any) => { this.groups = rsp; this ...

Issue with rendering the search component due to a conflict with validate.js

I am currently facing an issue with my search component that includes validation using JavaScript. The problem I am encountering is that when I first focus on the input, the validation and request do not work. However, after losing focus on the input, cli ...

Learn how to resolve the issue of "Property 'item' does not exist on type 'never'." in Angular using TypeScript with the following code snippet

addToCart (event: any) { if ("cart" in localStorage) { this.cartProducts = JSON.parse(localStorage.getItem("cart")!) console.log(event); let exist = this.cartProducts.find(item => item.item.id == event.item.id); ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

The value is not being found in my form, and the slide-toggle is consistently checked

I am encountering an issue with my forms. On the web, all my slide-toggle options are pre-checked as shown in the image provided. I suspect that the problem lies within the patchFor(){} function. Could someone please review my code for me? I have attempte ...

Modify associated dropdown menus

I am trying to create an edit form that includes dependent select fields (such as country, state, city). The issue I am facing is that the edit only works when I reselect the first option (car brand) because I am using the event (change) with $event. How c ...

The significance of zone.js and rxjs within the context of Angular 2

As a newcomer to Angular2, I recently learned about zone.js and rxjs. I'm curious to know if they both serve the same purpose for handling asynchronous tasks, or if each has its own specific role. Can someone explain to me the exact reasons why zone.j ...

Conceal or eliminate webpack from Angular 2 framework

Currently immersed in an Angular 2 project with TypeScript. Desiring to conceal or eliminate webpack from the developer tool. Came across information about uglify but it remains somewhat puzzling. See the image below for a glimpse of the Chrome Developer ...

Retrieving ACCESS_TOKEN from Instagram redirect using Angular 5 (Implicit Authentication)

Building a frontend app without a backend, I have decided to use Instagram implicit authentication. However, once the user authorizes the app, Instagram redirects to my redirect_uri with the access token in this format: http://your-redirect-uri#access_to ...