Limit the keys in TypeScript to only the elements of an array

Modified: Updating ID Types

I have an array that contains the following values:

const ids: number[] = [45, 56];

const obj: any = {
  45: "HELLO",
  56: "WORLD",
};

I want to specify a type for my object to only allow values that are in my ids array.

I attempted to use a lookup type but didn't achieve the desired result...

Any suggestions?

Thank you

Answer №1

To store the literal types of array elements, you can utilize the Record mapped type along with a const assertion:

const numbers = [12, 24] as const;

const data: Record<typeof numbers[number], string> = {
    12: "GOOD",
    24: "DAY",
};
const data2: Record<typeof numbers[number], string> = {
    12: "GOOD",
    24: "DAY",
    25: "MORNING",  // error
};

Answer №2

If you're looking to create a function that generates an object with type-checkable keys corresponding to an array, you can use the following code:

function generateKeys<K extends string>(keys: readonly K[]) {
  type Output = Record<K, number>;

  const result: Output = {} as Output;

  const {length} = keys;

  for (let i = 0; i < length; i++) {
    const k = keys[i];

    result[k] = i;
  }

  return result;
};

If you try to access a key that doesn't exist in the generated object, the type-checker will raise an error:

// Property 'zz' does not exist on type 'Output'.
const {aa, zz} = generateKeys(['aa', 'bb']); 

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 best way to format a string into a specific pattern within an Angular application

In my Angular component, I have 4 fields: customerName, startDate, and startTime. Additionally, I have a fourth field that is a textarea where the user can see the message that will be sent via email or SMS. Within my component, I have defined a string as ...

Rows in angular ag grid are vanishing when data is filtered

My ag grid includes custom components for each column, but I'm facing an issue where the components disappear when filtering the data. For example: the component inside the row To apply filtering, I use an input with a filtering function: <data-gr ...

Injecting AngularJS together with TypeScript and Restangular to optimize application performance

Encountering an issue while trying to configure my angularjs + typescript application with the restangular plugin Here are the steps I have taken: Ran bower install --save restangular (now I have in index.html <script src="bower_components/restang ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

Issues have arisen with the ReactNative Jest snapshot test, resulting in a

I decided to incorporate TypeScript into my react-native project. I came across this helpful article and followed the instructions step by step. However, when I ran yarn test, I encountered an error that I'm unsure how to resolve: FAIL Components/__ ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

Search through the directory of images and generate a JSON representation

I'm looking for a way to transform a URL-based directory of images into a Json object, which I can then utilize and connect within my Ionic project. Despite extensive searching, I have yet to find any satisfactory solutions to this challenge. Thus, I ...

Angular application code modifications do not reflect in the browser

After making changes to the HTML file of an Angular component, the browser does not reflect those changes when connected to localhost. Even though the old string is no longer present in the project, the browser continues to display it. Interestingly, openi ...

Attempting to render the application results in an error message stating: "Actions must be plain objects. Custom middleware should be used for asynchronous actions."

I am experiencing an issue while testing my vite + typescript + redux application to render the App component using vitest for testing. I am utilizing redux@toolkit and encountering a problem when trying to implement async thunk in the app component: Error ...

Challenges with deploying Angular applications and dealing with undefined properties within Angular code

Currently, I have successfully added new products to the database with all the desired properties. However, I am facing errors that are preventing me from deploying the application for production. Fixing these errors causes further issues where I cannot ad ...

A method for handling specific subsets of an enum in a secure and controlled manner

I have an enumerated type called Country and another type that represents a subset of European countries. I want to handle values within this subset differently from others. Currently, I am using an if statement with multiple conditions, but it could get u ...

Issues with the functionality of Angular 2 routerLink

Unable to navigate from the homepage to the login page by clicking on <a routerLink="/login">Login</a>. Despite reviewing tutorials and developer guides on Angular 2 website. Current code snippet: index.html: <html> <head> ...

Bring in TypeScript property from an external scope into the current scope

I am encountering an issue with my TypeScript code. Inside the anonymous functions, I am unable to change the properties of the class because they are out of scope. Is there a way to pass them in so that they can be modified? class PositionCtrl { ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

Step-by-step guide on importing `block-ui`, `spectrum-colorpicker`, and `sass.js` libraries in a TypeScript project

I have been utilizing various plugins such as block-ui, spectrum-colorpicker, sass.js, etc., in my Angular 2 project written in TypeScript. Currently, I am loading these plugins directly in the index.html file. However, I would like to import them and onl ...

Establish a table containing rows derived from an object

I am currently dealing with a challenge in creating a table that contains an array of nested objects. The array I have follows this schema: array = [ { id: 'Column1', rows: { row1: 'A', row2 ...

Guide to invoking the API prior to shutting down the browser window in Angular4

Currently, I am working on an Angular 4 application that consists of 5 components. My goal is to trigger an API call when the user closes the browser window from any one of these components. However, I have encountered an issue where the API does not get ...

How to Retrieve Input Field Value Using Cypress Custom Command

Is there a way to retrieve the value of an input[text] element within a custom command? Cypress.Commands.add('extendValue', { prevSubject: 'element' }, (subject: JQuery<HTMLElement>, extension: string): any => { const r ...

Remove the package from the @types folder within the node_modules directory

I currently have the 'mime' library in my node_modules directory and I am looking to completely remove it from my project, along with its @types files. The reason for this is that the old mime package is not functioning correctly for me, so I wan ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...