Utilizing TypeScript to define object key types based on a subset of keys from a generic type

Is there a way to create an object with keys that are a subset of the keys of a generic type?

I am exploring options for defining a type for the headers parameter, which should be a subset of the keys of 'T' mapping to string values.

export abstract class Table<T> {
  constructor(
    protected data: T[],
    //this currently requires the headers object to include all keys in T
    protected headers: { [key in keyof T]: string },

    //however, I am looking for a solution like this
    protected headers: { [keyof T]: string }
  ) {}
  //...abstract methods
}

//example
interface User {
  username: string;
  password: string;
  age: number;
}

class UserTable extends Table<User> {
  constructor(data: User[]) {

    //the current implementation does not compile as it lacks all keys from User
    super(data, {
      username: 'User',
      age: 'Age',
    });
  }
}

Answer №1

To create a type with the same keys as T but of type string, you can utilize the Record utility type. Additionally, to make the keys optional, you can employ the Partial utility type:

export abstract class Table<T> {
  constructor(
    protected data: T[],
    // Ensure the headers object contains all keys in T
    protected headers: Partial<Record<keyof T, string>>,
  ) {}
  //...abstract methods
}

//example
interface User {
  username: string;
  password: string;
  age: number;
}

class UserTable extends Table<User> {
  constructor(data: User[]) {

    // This does not compile as it doesn't include all keys from User
    super(data, {
      username: 'User',
      age: 'Age',
    });
  }
}

For experimentation and illustration purposes, check out this Playground Link

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

Displaying Typescript command line options during the build process in Visual Studio

As I delve into the world of VS 2015 Typescript projects, I find myself faced with a myriad of build options. Many times, the questions and answers on Stack Overflow mention command line options that I'm not completely familiar with, especially when i ...

Stop const expressions from being widened by type annotation

Is there a way to maintain a constant literal expression (with const assertion) while still enforcing type checking against a specific type to prevent missing or excess properties? In simpler terms, how can the type annotation be prevented from overriding ...

Performing Cypress testing involves comparing the token stored in the localStorage with the one saved in the clipboard

I am currently working on a button function that copies the token stored in localStorage to the clipboard. I am trying to write code that will compare the token in localStorage with the one in the clipboard in order to verify if the copy was successful. H ...

Conceal component (Ionic React TypeScript)

I was wondering about a specific situation in my code. Here is the relevant snippet: const Dashboard: React.FC<RouteComponentProps> = ({ history }) => { var random = 1; return ( <React.Fragment> <IonTitle id="title&qu ...

Can discriminated unions solely be utilized with literal types?

When looking at the code snippet below, I encountered an issue with discriminating the union type using the typeof operator. function f(arg: { status: number; one: boolean } | { status: string; two: boolean }) { if (typeof arg.status === "number&q ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Verification function in cypress to ensure accurate display of specific timeframes

Looking to create a Cypress method for checking three different rounding cases regarding the hour. An example of the second case I want to include in a general method, if a specific argument is provided: ( cy.contains('00') && cy.contain ...

A guide on transitioning from using require imports to implementing ES6 imports with the concept of currying

Currently in the process of migrating a Node/Express server to TypeScript. I have been using currying to minimize import statements, but now want to switch to ES6 import syntax. How can I translate these imports to ES6? const app = require("express")(); ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

TSX implementation of a paginator with an ellipse in the center

Looking to add ellipses in the Pagination, specifically when there are more than 10 pages (e.g., 1 2 3 4 ... 11 12 13 14). I've tried various methods but need guidance as a beginner. Can anyone suggest changes based on my code to help me achieve this? ...

Django and Angular combine to create a floral mapping feature that allows users to easily return to their task list

I am looking to arrange the output from the flower library (/api/tasks) into a list of objects. The current response includes multiple objects, but lacks a "list wrapper", making it difficult to iterate over. API: An example of the return is as follows: H ...

Is there a way to differentiate between a plain object and a class instance in Typescript?

Specifically, I am looking to differentiate between primitive types and plain objects versus class instances. let x = {y:5} // this is acceptable class X { y = 5; } let x = new X(); // this is not permissible ...

How can TypeScript be used to access a state object conditionally using an array?

I have an issue with my object that has an extended state object. I created an array of values to check using a for of loop, but I am having trouble making the array value compatible with the state object's key. How can I inform TypeScript that the va ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...

"Is there a way to extract a value from a JSON object using

I have an object with the following key-value pairs: { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812', 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1&a ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

Is there an automatic bottom padding feature?

Currently, I am facing a challenge in fitting the loader into the container without it being overridden by the browser. Using padding-bottom is not an ideal solution as it results in the loader appearing un-resized and unprofessional. Any suggestions or co ...

Hold off until the asynchronous function has completed - Ionic2

I am developing in Ionic2 and encountering an issue: Within my component, there is a method called drawPlayer that fetches data from a Firebase database. Here is the code for this method: drawPlayer(){ this.playerData.drawThePlayer().on('value&a ...

What is the abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...