I'm looking to convert this typescript function to return an array with strong typing instead of just a plain string[]

I am currently in the process of converting a JavaScript function to TypeScript. Originally, I believed that the type of the variable hi would be ('s'|'bb')[], but it turned out to be string[]. Is there a way for TypeScript to automatically infer K to be the keys of NewOptions?

export const getWithOverrides = <
  K extends string,
  NewOptions extends { [x in K]?: boolean },
  Overrides extends { [x in K]?: boolean }
>(
  newOptions: NewOptions,
  overrides: Overrides
): K[] =>
  (Object.keys(newOptions) as K[]).filter(key => {
    if (typeof overrides[key] === 'boolean') {
      return overrides[key];
    }
    return newOptions[key];
  });

const hi = getWithOverrides({ s: true, bb: true }, { s: true });

Answer №1

To achieve this, you can eliminate the K type parameter, set the requirement that object types must extend from Record<string, boolean>, and apply keyof to both object types:

export const getWithOverrides = <
    NewOptions extends Record<string, boolean>,
    Overrides extends Record<string, boolean>
>(
    newOptions: NewOptions,
    overrides: Overrides
): (keyof NewOptions | keyof Overrides)[] =>
    Object.keys(newOptions).filter((key) => {
        if (typeof overrides[key] === "boolean") {
            return overrides[key];
        }
        return newOptions[key];
    });

const hi = getWithOverrides({ s: true, bb: true }, { s: true });
//    ^? const hi: ("s" | "bb")[]

Playground example

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

Performing a JSON AJAX call that sends a null object to a Java class

Within my JavaScript file, I am utilizing the following getJSON method like so: $.getJSON('do/ajax-convertlocaldatetime', { timestamp : localdatetime, The localdatetime variable is an instance of a LocalDateTime object. This ajax call trigg ...

Error received - CORS request denied on Firefox browser (Ubuntu)

I encountered a CORS error (CORS request rejected: https://localhost:3000/users) while attempting to register a new user. This issue arose from content in the book Building APIs with node.js, Chapter 12. I am currently using Firefox on Ubuntu and have tr ...

Struggling to render images within a child component in a React application when passed as a prop from the parent component

Currently immersed in a React project, here is the structured layout of my work: public index.html src App.js images facebook.png image.PNG linkedin.png profile.png twitter.png Profile Intro profileIntro.js data data.js Within App.js, I import ...

Using Redux with Next.js to implement getStaticPaths

Can someone help me understand how to implement getStaticPaths in conjunction with Redux in Next.js? I'm currently using next-redux-wrapper to manage my content, but I am encountering issues when trying to display the data. Below is a snippet of my ...

Disabling ion-select in Ionic 2 with Typescript

To disable an ion-select element in Angular, you can use the disabled attribute like this: <ion-item> <ion-label stacked>Property Type</ion-label> <ion-select [(ngModel)]="propType" (ionChange)="ionChanger()" di ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

Finding Child Elements in JavaScript with Specific Attribute

I have an item that was obtained using this expression: const item = document.querySelector("...my selector..."); I am trying to access all child items with specific attributes. The method I currently use to retrieve all children is: const children = Ar ...

"Learn the technique of animating SVG paths with JavaScript, a step beyond traditional HTML filling

I am looking to animate SVG path elements with JavaScript instead of HTML. I have come across numerous articles discussing how to achieve this through JavaScript and jQuery by manipulating the attributes. Some helpful links I found: Fill color SVG path w ...

Dealing with a Node and Express server can be tricky, especially when trying to proxy a POST request along with parameters. You might encounter the error

I am trying to forward all requests made to /api/ from my local node server to a remote server, while also adding some authentication parameters to them. Everything works smoothly for GET requests with query parameters and POST requests without specifying ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

What is the process of obtaining User properties through a URL and utilizing them as variables in JavaScript?

I need to retrieve the city properties: 918 using req.params.userMosque from the URL '/shalat/:userMosque'. I want to assign it to the variable city for customizing my API url request. However, it seems like it's not working as expected. I h ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

jquery hover effect not functioning properly

I have a question regarding my jquery mobile application. I am trying to implement a hover effect on items with the class grid-item, where the width and height change simultaneously in an animation. Here is the code snippet I am using: $('.grid-i ...

The GraphQl Code Generator fails to correctly generate the graphql() function in Next.js applications

While working on my next.js project, I integrated GraphQL to generate types for queries. However, the code generator is not functioning properly and displaying an error message: "The query argument is unknown! Please regenerate the types." within the gql.t ...

What is your approach to converting this jQuery code to ES6 syntax?

The concept involves gathering all the links and corresponding IDs, and hiding inactive content. When a link is clicked, the associated content should be displayed. The Structure <div class="navbar"> <nav> <ul class="navTabs"> ...

Navigate the page by scrolling the absolute positioned div

Is it possible to make the fancybox modal scroll with the page using fancybox 2? I want it to move along with the content rather than being fixed in the center with a max-height restriction. How can I achieve this? $('.fancybox-open').fancybox({ ...

Direct your attention solely on the input fields and buttons

Is it possible to restrict focus to specific elements, such as input fields and buttons? For example, if a user is focused on an input field and then clicks somewhere else on the page, the input field should retain focus. But if the user clicks on another ...

Creating a non-editable form or text field upon clicking the Submit button

<form [formGroup]="calculateForm"> <div class="form-group row"> <p for="inputFrom" class="col-sm-4">Distance traveled ...

The data retrieved from the API call is outdated

I am struggling with a weather web API that is only showing old data when called in the code. However, when I enter the API URL directly into the browser, it displays the most up-to-date information for the current city. Can anyone help me troubleshoot why ...

What is the best way to include a JavaScript function in a dynamically generated div?

By clicking a button, I am able to dynamically generate a table row that contains a div element with the class "contents." $(document).on("click", ".vote", function() { // Removing selected row var rowLoc = this.parentNode.parentNode. ...