Limit the values in the array to only match the keys defined in the interface

I'm trying to restrict an array's elements to specific keys of an interface:

interface Foo {
  bar: string;
  baz: number;
  foo: string;
}

type SelectedKeysArray<T, K extends keyof T> = Pick<T, K>[];

const selectedKeys: SelectedKeysArray<Foo, "bar" | "baz"> = ["bar", "baz"]; // Error: Type 'string' is not assignable to type 'Pick<Foo, "bar" | "baz">'

Answer №1

If you want to achieve this task effortlessly, you can utilize the Extract utility type in TypeScript. Here's an example:

type AllItems = keyof Items
type SelectedItems = Extract<keyof Items, 'selectedItem' | 'anotherSelectedItem'>

const allItemsValid: AllItems[] = ['selectedItem', 'anotherSelectedItem', 'item']
const allItemsInvalid: AllItems[] = ['selectedItem', 'invalid'] // Type '"invalid"' is not assignable to type '"selectedItem" | "anotherSelectedItem" | "item"'

const selectedItemsValid: SelectedItems[] = ['selectedItem', 'anotherSelectedItem']
const selectedItemsInvalid: SelectedItems[] = ['selectedItem', 'item'] // Type '"item"' is not assignable to type '"selectedItem" | "anotherSelectedItem"'.

Take a look at this Playground for a demo.

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

When attempting to retrieve and process a JSON from the internet, I encounter "undefined" errors despite the fact that the data appears correctly in the log

I'm having trouble processing the JSON data received from a server. When I attempt to use .forEach on it, I receive an error stating that the data is undefined even though the console.log shows the correct values. What could be causing this issue? Is ...

Creating a TypeScript function that can dynamically assign values to a range of cells within a column, such as AD1, AD2, AD3, and so on

Hello there I'm currently working on a function that will dynamically assign values to the column range of AE to "AD" + i. However, when I use the function provided below, it only writes AD5 into the first 5 columns instead of AD1, AD2, AD3, and so o ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

Invoking a subclass's method within a base class in Typescript

Currently, I am in the process of developing a small game project and I am facing a particular challenge that I need a solution for. Within my code, I have a base class called 'Entity' which contains essential methods for its subclasses (objects ...

When trying to set the focus on the first item in a list using HTML and Angular, the focus unexpectedly shifts to the second

I've been tackling a UI requirement where the focus needs to be set on the first element of a list item constructed from an array of objects when the tab key is pressed for the first time. Subsequent tab key presses should cycle through the list items ...

Steps to develop a sub-route specifically for a single word

Take a look at this code: {path : 'recipes', component:RecipesComponent, children:[ {path:':id', component:RecipeDetailComponent}, {path:':new', component:NewRecipeComponent } ]}, No matter which link you use: h ...

Tips for accessing the nested formArray value using a getter in Angular

I am currently attempting to retrieve form values using the getter method and then dynamically pushing them to update the form with values. However, I am faced with a nested array at the moment, which is causing issues with retrieving the form values. Bel ...

React with TypeScript is throwing an error that says: "The type 'string' does not have any properties in common with the type 'CSSProperties'."

Currently encountering a challenge while using Typescript in conjunction with React. https://i.sstatic.net/tHkoJ.png ...

Learn how to retrieve the return data from two combined objects using Angular's TypeScript syntax

I've encountered an issue with TypeScript syntax, specifically when a WebAPI returns a DTO containing two objects. The object being returned looks like this: { "userList": [{ "id": 1, "firstNm": "John", "lastNm": "Doe" }, ...

The collaboration of React hooks, typescript, mongoose, express, and socket.io in perfect harmony

I am currently working on setting up a frontend React app to communicate with a NodeJS Express API using socket.io import React, { useEffect, useState } from "react"; import io from "socket.io-client"; const socket = io("http://lo ...

Is it possible to run NestJS commands without relying on npx?

I recently installed nestjs using npm, but I encountered an issue where it would not work unless I added npx before every nest command. For example: npx nest -v Without using npx, the commands would not execute properly. In addition, I also faced errors ...

JavaScript code for sorting a list of objects alphabetically according to a different list

I am looking to alphabetically sort a list of objects based on another list of characters and the 'name' property. Below is the sorting order I would like to use: const SortingArray = [['a','á','à','â', ...

Learn how to alter the website's overall appearance by changing the background or text color with a simple click on a color using Angular

Is there a way to dynamically change the background color or text color of the entire website when a user clicks on a color from one component to another? I know I need to use the Output decorator, but how can I implement this? style.component.html <di ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

There is no index signature that includes a parameter of type 'number' on the specified type xx

Here are the data types I am currently utilizing: export interface IHelpDeskTextData { supportPaneltext: ContactHelpdeskContex[]; selected?: number | null; brandOptions?: string[]; textPanel?: ITextPanel[]; } export class ContactHelpdeskContex { ...

What is the best way to create a versatile svelte component that can be utilized across various projects?

Currently, I am in the process of developing two distinct web applications using svelte/typescript: Site A, which serves as the public-facing front end and must be optimized for speed and efficiency Site B, the administration UI where editors manage and u ...

Using Element as a type parameter in a React/Typescript function

In my React project using Typescript, I am working on creating a generic collection. The current setup is as follows: class List<T> { constructor(data: any){...} } This code allows me to create a list of a specific type. My goal is to perform a ...

Tips for manually inputting dates in Primeng Calendar Datepicker with the slash "/" symbol

I need assistance with adding slashes to manual input when using the primeng Calendar component. <p-calendar [monthNavigator]="true" [yearNavigator]="true" yearRange="1950:2021" ngModel [required]="tru ...

Issue encountered while executing ./node_modules/.bin/cucumber-js within GitLab CI

I've encountered an issue while setting up a continuous integration build for my node project. Despite the fact that npm run test runs smoothly in my local setup, I am facing an exception in GitLab CI. The error arises from the following test command ...