The parameter type 'string[]' cannot be assigned to the parameter type '("a" | "b" | "c")[]' in TypeScript


/**
 * Function to pick specific keys from an object.
 */
function pick<T, K extends keyof T> (obj: T, keys: K[]): Pick<T, K> {
  return keys.reduce((result, key) => {
    result[key] = obj[key];
    return result;
  }, {} as any);
}

const keys = ['b', 'c'];
const o = {a: 1, b: '2', c: 3};
const picked = pick(o, ['b', 'c']); // This is valid
const picked2 = pick(o, keys); // This will produce an error

Error message: Argument of type 'string[]' is not assignable to parameter of type '("a" | "b" | "c")[]'.

If you only want to dynamically select keys, consider using a union type for the keys instead of an array of strings.

Answer №1

keys is initially defined as an array of string[], but when utilized with Pick, it forms string-literal types. To resolve this inconsistency, you can create a type for variable o and employ keyof with that particular type. One approach to address this with minimal modifications would be:

const o = {a: 1, b: '2', c: 3}
const keys: (keyof typeof o)[] = ['b', 'c']

An attempt to assign values outside the scope such as

const keys: (keyof typeof o)[] = ['b', 'd']
will still result in an error, ensuring the desired level of type safety.

To further enhance clarity, I suggest defining a specific type for o and incorporating it, for instance:

interface O {
  a: number;
  b: string;
  c: number;
}
const keys: (keyof O)[] = ['b', 'c']

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

Invoking a subclass method's constructor using a generic parameter

The code below is not passing the type-checking: type MyFunctionConstructor<T, F extends MyFunction<T>> = new ( f: (n: number) => T ) => F; class MyFunction<T> { constructor(f: (n: number) => T) { this.f = f; } f: ...

Breaking down paginated requests in Apollo Client that target the same field name but employ distinct filters

Utilizing relayStylePagination was a seamless process for me in creating a paginated feed of Post objects for users on my app. Nevertheless, I have the desire to employ the same field and pagination method but with a filter for a specific user when accessi ...

Assessing the invalidity of user-defined type guards within class implementations

I just wrote this Typescript code and tested it in a sandbox. Check out the code snippet below: class Foo { public get test() : string|number{ return "foo" } public hasString() : this is { test:string }{ return type ...

Exploring Angular 12: Techniques for Monitoring Property Changes in a Service

Within my current project, there exists a series of dependencies. Specifically, there is a shared service class containing an object named "myObject" which many components access and modify. The issue at hand is that each component is independently modifyi ...

Executing numerous TypeScript 'tsc' commands

I'm currently working on setting up an NPM command to transpile two separate Typescript projects located in subdirectories within my application, followed by starting the server. Within my 'src' public folder, I have 'Server' and ...

A generic TypeScript with the ability to extend optionally

How can I modify the generic ApiResBook type to handle optional props with input check using the extends keyword? Sandbox. I have these main types defined, which correspond to fields in a database: // Main types as in database - should't be changed ...

What is the best way to send a JSX Element as a Prop using React and Typescript?

I need help passing an Icon as a Prop to my TextInput Component in this way: export interface TextInputProps { leadingIcon?: (props: React.ComponentProps<'svg'>) => JSX.Element } export const CustomTextField = forwardRef<HTMLInputE ...

Managing file imports in Angular 2+ Unit Testing

Within my project, there are various utility functions that handle data transformations and other tasks. These functions are not contained within a class and are utilized across multiple utility files. Being relatively new to angular testing, I've sp ...

Guide to loading TypeScript modules with RequireJS in an ASP.NET MVC/Visual Studio setup

If we consider a scenario where there are 2 files named test1.ts and test2.ts. The content of test1 is as follows: export const x = 1 And the content of test2 is: import { x } from './test2' alert(x); Upon running the application, an error m ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

When users install my npm module, they are not seeing text prediction (intellisense) in their editors

I'm currently focused on developing my package @xatsuuc/startonomy. I'm encountering an issue where Intellisense is not working properly when the package is installed on the user's side. Even though the .d.ts files are visible in node_modul ...

NestJS enforces HTTPS for Swagger redirects, whereas other endpoints are allowed to work on HTTP

I'm running into a strange problem with the Swagger interface on my NestJS server, which is hosted on a Windows Server environment and managed by PM2. While all other endpoints work fine over HTTP, the Swagger interface can only be accessed via HTTPS. ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Having trouble sending a x-www-form-urlencoded POST request in Angular?

Despite having a functional POST and GET service with no CORS issues, I am struggling to replicate the call made in Postman (where it works). The only thing I can think of is that I may have incorrectly set the format as x-www-form-urlencoded. When searchi ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

How to Toggle Visibility of Angular2 Material Drop Down Menu?

My Code <mat-form-field class="button-spacing"> <mat-select placeholder="select" [(ngModel)]="dropDownOne"> <mat-option *ngFor="let first of test1" [value]="first"> {{ first }} </mat-option> </mat-select> </mat-fo ...

"An issue of type TypeError occurred: When logging out of the application, it appears that 'x is null

Currently in my app, I am working on implementing authentication following the guidance provided in this example: Click here for more information. However, I have encountered an error that reads "ERROR TypeError: 'x is null'" when trying to execu ...

Breaking down large reducer into smaller reducers

I am currently working on a feature reducer (slice reducer) called animals. My goal is to separate these reducers into categories such as mammals, birds, fishes, and more. Initially, I thought this would be a smooth process using the ActionReducerMap. How ...

What is the proper way to utilize queries in BlitzJS?

I am attempting to extract data from a table by filtering based on the relationship with the Blitzjs framework. However, I am facing difficulties using queries as it seems to be the only option available. Every time I try to call the quer ...