Enter the output of a function that includes keys found within a given array of elements

Here's a function I've been working on:

type Action = 'doX' | 'doY'
function canIPerform(actions: Action[]) : {[action: string]: Boolean} {
    // Some business logic
    return {'doX': true}
}

My goal is to type it in a way that ensures the returned map only includes keys that were passed in the argument:

let x = canIPerform(['doX'])
// x should be typed as {[k in 'doX']: boolean}

let x = canIPerform(['doY', 'doX'])
// x should be typed as {[k in 'doX' | 'doY']: boolean}

The challenge lies in the fact that arrays are evaluated at runtime, but I've found a workaround by utilizing const:

let x = canIPerform(['doX', 'doY'] as const)

I have attempted various approaches to enforce this behavior, but haven't discovered an equivalent of keyof that functions effectively for tuples.

Answer №1

Is this the solution to your problem?

type Action = 'doX' | 'doY'
function canIPerform<T extends Action[]>(actions: T) : Record<T[number], boolean> {
    // Implementing some business logic here
    return { [actions[0]]: true }
}
let x = canIPerform(['doX'])
//  ^?
// Variable x should have a type of {[k in 'doX']: boolean}

let y = canIPerform(['doY', 'doX'])
//  ^?
// Variable y should have a type of {[k in 'doX' | 'doY']: boolean}

x and y will essentially be equivalent to the types you specified.

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

The Angular template loads and renders even before the dynamic data is fetched

I'm encountering a frustrating issue where the page loads before the data is retrieved. When I log the names in $(document).ready(), everything appears correct without any errors in the console. However, the displayed html remains empty and only shows ...

Guide to implementing an "export default" with various types and values in a TypeScript module

There is a simple way to export multiple values as default: class Car {...} class Bus {...} export default { Car, Bus } You can also easily export a type as default export default interface Airplane {...} However, exporting multiple types as default i ...

Displaying data issue with Typescript typed array

While working with Angular 7 and Typescript 3, I encountered an issue where I was trying to pre-populate an array of ingredients in a service for use in a component. However, when I checked the console output, the array was showing empty objects. If I ini ...

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Adjust Column Title in Table

Is it possible to customize the column headers in a mat-table and save the updated value in a variable? I've been looking for a solution to this but haven't found one yet. ...

Issues arise with Shared Module imports not functioning properly within Shared components following an upgrade to Angular 9

I recently updated my project to the following versions: Node from 11 -> 12 Angular from 8 -> 9 After the upgrade, I started encountering compile time errors in my application. The application consists of numerous shared components that are declare ...

What benefits could you derive from utilizing an interface to generate a fresh Array? (Pulumi)

Just delving into the world of TypeScript and Pulumi/IaC. I'm trying to wrap my head around a code snippet where an array of key values is being created using an interface: import * as cPulumi from "@company/pulumi"; interface TestInterface ...

What is the best way to utilize the fresh Sanitizer API in Typescript?

Everything seems to be working well on Codepen, even without using window. It's surprising because I'm used to having to use window.x if ( 'Sanitizer' in window ) { console.log( 'sani', 'Sanitizer' in window ); } ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

Utilize the term "export const" twice when declaring variables to assign value

const foobar = { foo: 'hello', bar: this.foo }; The code isn't working as expected, returning "undefined". Any suggestions on how to properly access it? ...

Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far. My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question: ...

"Utilizing the range option in a NodeJS request proves ineffective when attempting to stream HTML5

I have set up a nodejs request to serve videos with range support. The backend code looks like this: import { createReadStream, statSync } from 'fs'; const stats = statSync(path); const range = request.headers.range; const parts = ra ...

Navigating through the typings directory in Visual Studio 2015

Is it necessary to include the typings folder as part of an asp.net application in Visual Studio 2015 when using typings? I would like to handle the typings folder similar to the bower_components folder - not checking it and not including it in my solutio ...

VIDEOJS ERROR: A peculiar mistake has occurred. TypeError: The property 'value' cannot be read since it is undefined in the context of

Recently, I came across a fascinating plugin called videojs-thumbnails for video.js, and I'm eager to incorporate it into my angular component. However, I keep encountering an error that says: VIDEOJS: ERROR: TypeError: Cannot read property 'val ...

Are you looking to resolve TypeScript warnings related to imports managed by Webpack loaders?

Setting up a new project with Svelte, Webpack, and TypeScript based on this template. Ran the scripts/setupTypeScript.js script to switch to TypeScript after initial setup. Encountering errors in VSCode and TypeScript when importing non-TypeScript files: ...

Executing an Observable function in Angular Typescript a single time

Within my Angular application, there exists a service responsible for retrieving data from a server. load.service.ts: load = new Observable(observer => { console.log('load function called'); // asynchronous tasks with time delay obser ...

Error: Module './App' not found in webpack module

I am encountering the error Uncaught Error: Module not found: Can't resolve ./App' and ./store in client/src. in the console of my local environment when I execute npm start from the client directory. The console is showing 2 errors: ERROR in ...

Exploring deeply nested arrays of objects until a specific condition is satisfied

My array is structured in a nested format as shown below. const tree = { "id": 1, "name": "mainOrgName", "children": [ { "id": 10, "name": "East Region", "children": [ ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...