Guide to incorporating a pluck feature into TypeScript code

One task I face frequently is extracting specific properties from an object

const obj = {a:1, b: 2, c: 3};
const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2}

Unfortunately, achieving this task with type safety in TypeScript can be challenging. Implementing a function with the signature mentioned in TypeScript's documentation isn't straightforward.

declare function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K>;

I attempted to create my own version without success. Here is the code snippet I tried:

function pluck<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
    // Type '{}' is not assignable to type 'Pick<T, K>'.
    const ret: Pick<T, K> = {};
    for (let key of keys) { 
        ret[key] = obj[key];
    }
    return ret; 
}

Does this mean I am required to use ambient declarations and define the function in JavaScript instead?

Answer №1

Utilizing the any keyword on the object being manipulated satisfies TypeScript, which allows it as a valid return value. See it in action

function pluck<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
    const ret: any = {};
    for (let key of keys) { 
        ret[key] = obj[key];
    }
    return ret; 
}

const less = pluck({ a: 1, b: '2', c: true }, ['a', 'c']);

Answer №2

Consider this different approach:

const extractValues = <T, K extends keyof T>(objects: T, properties: K[]): Pick<T, K> => {
  return properties.reduce((result, property) => 
    Object.assign(result, {[property as string]: objects[property]}), {}) as Pick<T, K>;
}

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

React Native: Issue with the data section in FlatList

I encountered an issue while using Flatlist to address a problem, but I ran into an error with the data property of my Flatlist. The error message is not very clear and I'm having trouble understanding it ( No overload matches this call. Overload 1 of ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Trouble arises when attempting to import React JSX project/modules from npm into an AngularJS TypeScript module

In the process of developing a proof-of-concept React framework/library, I aim to create a versatile solution that can be utilized in both React and AngularJS applications. To achieve this goal, I have initiated two separate projects: - sample-react-frame ...

The onClick event in HostListener is intermittent in its functionality

While attempting to create a dropdown box in Angular by following these examples, I am encountering inconsistent results. Below is the code I have used: HTML <button (click)="eqLocationDrop()" id="eqLocButton"><i class="fas fa-caret-down">< ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Why is it that the Jasmine test is unsuccessful even though the 'expected' and 'toBe' strings appear to be identical?

I have been developing a web application using Angular (version 2.4.0) and TypeScript. The application utilizes a custom currency pipe, which leverages Angular's built-in CurrencyPipe to format currency strings for both the 'en-CA' and &apos ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

The variable isJoi has been set to true but there is an error due to an unexpected

I am currently developing a NestJs backend on multiple machines. One of the machines is experiencing issues with the @hapi/joi package. When running the NestJs application in development mode on this specific machine, I encounter the following error: PS C ...

Checking for undefined based on certain conditions

When looking at the following code snippet type stringUndefined = "string" | undefined; type What<T> = T extends undefined ? "true" : "false"; const no : What<stringUndefined> = ""; The value of ' ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. https://i.sstatic.net/CZTO2.png The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it s ...

Issue with maintaining variable state in Angular 7 service component

I currently have 2 components and a single service file in my Angular project, which consist of a login component and a dashboard component. The issue arises when I try to access the user data from the service file. In the login component, the user data i ...

Exploring the integration of multiple HTTP requests in Angular with the power of RxJS

Is there a way to make multiple HTTP calls simultaneously in an Angular service and then combine the responses into one object using RxJS? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; im ...

Error: Import statement not allowed outside a module when using Material UI

I am relatively new to material UI. In my React project, I am incorporating material UI components. I am trying to implement a customized radio button following the instructions in the Mui documentation: https://mui.com/material-ui/react-radio-button/#cust ...

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

Having trouble using the 'in' operator to search for 'Symbol(StrapiCustomCoreController)' while transitioning Strapi to TypeScript

I'm in the process of converting my strapi project to typescript. I've updated all strapi packages to version 4.15.5 and converted the files to ts extension. However, upon running strapi develop, I encounter the following error: [2024-01-03 10:50 ...

What methods can be used to block direct attribute updates in a JS/TS class?

class Creature { secretProperty modifySecretProperty(value) { this.secretProperty = value } } new Creature().modifySecretProperty('hidden way') //success new Creature().secretProperty = 'not permitted' // failure To r ...

"Encountering a build failure in Next.js when using getStaticProps because a parameter is returning undefined

An unusual error has recently surfaced, causing our builds to fail, Located within the pages directory is a post/[id].tsx file that utilizes getStaticProps and getStaticPaths -- props export const getStaticProps: GetStaticProps = async ({ params }) => ...

TypeScript(error:2532): object may be undefined despite null or undefined check

Currently, I am developing a Discord-bot using TypeScript which includes a command to retrieve information from an airport. To do this, users only need to provide the 4-character ICAO code that identifies the specific airport. However, due to potential use ...

Sending error messages from server to client (leveraging Express and Backbone)

I'm struggling with passing server error messages to a client after thrashing around for a while. Here's what I have on the server side (simplified): export function get(req: express.ExpressServerRequest, res: express.ExpressServerResponse) { ...