How can we design a return type for a function in Typescript that enforces the exact keys present in the input array K[] to be included in the Record?

I have a function that takes an array of Animals, and returns a map where the keys are the animals and the values are their fur colors:

export enum Animals {
  CAT = 'CAT',
  DOG = 'DOG',
  SEAL_PUP = 'SEAL_PUP',
}

const furColors = ['BROWN', 'BLACK', 'WHITE'];

function getFurColor(animals: Animals[]): Partial<Record<Animals, string>> {
  // call some internal service to get fur colors for each Animal, then return them as a Record. Here as example we randomly assign:
  return animals.reduce((acc, animal) => {
    acc[animal] = furColors[Math.floor(Math.random() * furColors.length)];
    return acc;
  }, {});
}

I want to specify the return type of this function in a way that when I make the following function call:

getFurColor([Animals.CAT, Animals.DOG]);

typescript indicates that the return type of this function is

{ ['CAT']: string, ['DOG']: string };

and if I attempt to access ['SEAL_PUP'] from the output, it will generate an error message

TS2339: property 'SEAL_PUP' does not exist on type { ['CAT']: string, ['DOG']: string }
.

Answer №1

You can declare it in the following manner

function getEyeColor<T extends Array<Pets>>(pets: T): Record<T[number], string> {
  throw new Error('not implemented')
}

TS 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

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

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 = ...

Reinforced.Typings does not generate fully qualified names (FQN) for types when UseModules is set to true or false

Overview: Within my solution, I have two projects: ProjA and ProjB. In ProjA, I've defined a custom RTConfigure method to streamline the configuration process for translating C# to TypeScript using the Reinforced.Typings tool. Meanwhile, ProjB houses ...

How can we efficiently load paginated data from a database while still implementing pagination using Angular Material?

I have a large table with more than 1000 entries that I want to display using a <mat-table></mat-table>. Since loading all the entries at once would be too much, I am looking to implement pagination and load only 20 entries per page. The chal ...

JSONPath encounters an issue when square brackets are embedded within a string

I am encountering issues with the JSONPath library found at https://github.com/JSONPath-Plus/JSONPath in its latest version. For example: { "firstName": "John", "lastName": "doe", "age": 26, ...

A guide to creating a forward reference in React

I have a complex component that I need to type accurately. Here is what I am trying to achieve: interface Selector<V,T> { onChange(value:V): T } export const Selector = forwardRef<V, T>( ( { onChange }: Selector< ...

What is causing my function to execute twice in all of my components?

One issue I am facing is that I have created three different components with routing. However, when I open these components, they seem to loop twice every time. What could be causing this behavior and how can I resolve it? For instance, in one of the comp ...

Implement endless scrolling to JSON dataset in an ionic-3 application

Is there a way to incorporate infinite scroll into my JSON array while initially displaying only 5 items? data:[ 0: Object { id: 123, title: "New family member Khjkjh has joined mymily", mm_family_id: 122, … } 1: Object { id: 124, title: "New family mem ...

Visual Studio 2015 is struggling to locate a specific module, yet the command line interface for

Recently, I delved into the world of TypeScript in VS2015 and so far, it has been a smooth journey. I managed to establish a structure that compiled and performed as anticipated. However, things took a turn when I attempted to incorporate npm-installed mo ...

Issues with Tagged Union Types in Visual Studio Code

Currently, I am working on implementing a tagged union type pattern for my action creators within a redux application. The TypeScript compiles without any issues, however, my code editor, Visual Studio Code 1.26.1, is flagging an error. [ts] Type &ap ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

Transforming a TypeScript enum into an array of objects

My enum is defined in this structure: export enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } However, I want to transform it into an object ar ...

Unable to utilize the Object.values method with an object in TypeScript

I am attempting to create an array of values from all the keys within an object by using the Object.values(obj) function, but I encountered the following error message: No overload matches this call. Overload 1 of 2, '(o: { [s: string]: string; } | ...

What is the best way to showcase a view on the same page after clicking on a link/button in Angular?

Is there a way to show a view on the same page in an Angular application when a link is clicked? Rather than opening a new page, I want it displayed alongside the list component. How can this be accomplished? Here's an illustration of my goal: I&apos ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Tips for sending code confirmation in Amazon Cognito identity using nest.js

Having some issues with implementing AWS Cognito login in Nest.js? Check out this helpful guide on token validation: https://medium.com/weekly-webtips/token-validation-with-aws-cognito-and-nestjs-6f9e4088393c. I need to add a feature where users receive ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

The parameter 'X' cannot be assigned to the argument of type 'X'

Hello there! I'm diving into Type Script for the first time with VSCode. Encountering these errors: error TS2322: Type '() => string' is not assignable to type 'string'. error TS2322: Type '() => number' is ...

The power of negative multiplication in TypeScript and React

I am working with a state variable called sortDirection const [sortDirection, setSortDirection] = useState<1 | -1>(1); My goal is to allow a button to toggle the state variable like this setSortDirection(sortDirection * -1); However, I encounter a ...