Ways to confirm if the indexed sort is an extension of a string

Suppose I have a function called func with 2 generic arguments

const func = <T extends {}, K extends keyof T>() => {};

and a type defined as

interface Form {
  a: boolean;
  b: string;
}

then I can call them without encountering any errors

func<Form, "a">();
func<Form, "b">();

Now, let's say I want the function to only accept keys for which T[K] = string In simpler terms

func<Form, "a">(); // should fail
func<Form, "b">(); // should pass

I attempted a pseudo-Typescript solution like this

const func = <T extends {}, K extends keyof T : where T[K] extends string>() => {};

however, it didn't go very far. Is such restriction even possible? I would appreciate any guidance on this matter.

Answer №1

By utilizing a small helper type, you can extract all the keys that have string values:

type StringKeys<T> = {
  [K in keyof T]:
    T[K] extends string ? K : never
}[keyof T]

type Test = StringKeys<{ a: boolean, b: string, c: string }>
// type: 'b' | 'c'

This specialized type loops through each property of T, keeping the key name if the value is a string and discarding it otherwise.

You can then apply this like so:

interface Form {
  a: boolean;
  b: string;
}

const func = <T, K extends StringKeys<T>>() => {};

func<Form, "a">(); // error
func<Form, "b">(); // fine

See Playground

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

Is there a way to access service data within an Angular interceptor?

I'm trying to include my authentication token in the request header within my auth.interceptor.ts. The value of the authentication token is stored in auth.service.ts. Below is the code for auth.interceptor.ts @Injectable() export class AuthIntercepto ...

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...

Upon the initial loading of GoJS and Angular Links, nodes are not bypassed

Hey there, I'm currently working on a workflow editor and renderer using Angular and GoJS. Everything seems to be in order, except for this one pesky bug that's bothering me. When the page first loads, the links don't avoid nodes properly. H ...

The ngFor directive encounters issues when placed within a quotation mark or when used within a Bootstrap Tooltip Tag

.HTML File : I encountered an error saying, "Identifier 'mg' is not defined." However, {{mgr[0].value}} works <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" ...

Ways to Prompt a User to Select the "Remember Me" Option

How can I implement the functionality of 'Remember Me' on a login page? I want users who click on 'Remember Me' to be able to reopen the page without logging in again, even after closing their browser. But how do I differentiate between ...

What is causing the error message "Module '@reduxjs/toolkit' or its type declarations are not found" to appear?

Although I have a good understanding of React-Redux, I decided to delve into TypeScript for further practice. Following the recommended approach from the react-redux team, I created a new project using the TS template: "npx degit reduxjs/redux-templa ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Potential solution for communication issue between Angular CLI and Flask due to cross-origin error

Initially, the user id and password are submitted from the UI (angular) to Flask: public send_login(user){ console.log(user) return this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions) .pip ...

Encountering an issue with d3 Angular 2 pie chart related to d3.arc data

I encountered a problem with my code: 'PieArcDatum' is not assignable to parameter of type 'DefaultArcObject.' at this specific line Argument of type return "translate(" + labelArc.centroid(d) + ")";. Could someone please assist me in ...

The NgRx Effect causing an endless cycle of HTTP requests

I am currently experiencing the following effect: initCompaniesAndSetCompanyEffect$: Observable<Action> = createEffect( (): Observable<Action> => this.actions$.pipe( ofType<changeCompanyActions.InitCompaniesAction>( ...

Ways to resolve the issue of the missing property 'ganttContainer' on the 'Gantt' type

I encountered an issue while trying to utilize the Gantt chart feature from the Dhtmlx library in TypeScript. The problem seems to stem from an error during the initialization of gantt. How can I go about resolving this? Below is the relevant code snippet: ...

What is the best way to choose an element within a component's template?

Is there a way to access an element that is defined in a component template? While Polymer has the $ and $$ to make this task simple, I am curious about how it can be done in Angular. Consider the example provided in the tutorial: import {Component} from ...

The ngfor loop seems to be caught in an endless cycle of continuously executing functions and

I am currently working on a sophisticated reporting solution. Essentially, I have created a table using an ngFor loop where I have implemented certain conditions that allow the user to view details of a clicked element by expanding and collapsing it. The ...

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 ...

Storing application state using rxjs observables in an Angular application

I'm looking to implement user status storage in an Angular service. Here is the code snippet I currently have: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() expo ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

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 ...

Error: Unable to access 'nativeElement' property from undefined object when trying to read HTML element in Angular with Jasmine testing

There is a failure in the below case, while the same scenario passes in another location. it('login labels', () => { const terms = fixture.nativeElement as HTMLElement; expect(terms.querySelector('#LoginUsernameLabel')?.tex ...

Leverage a custom server (such as NestJS) within NextJS to dynamically render targeted pages

I am experimenting with using NestJS as a custom server for NextJS, following the instructions in this article. Here is a simplified version of the code: @Controller('/') export class ViewController { @Get('*') async static(@Req() r ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...