Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this:

export const details = {
        x: {
            INFO_x: 'xxx'
        },
    
        y: {
            INFO_y: 'xxx'
        },
    
        z: {
            INFO_z: 'xxx'
        }
    };
    
    export const performAction = (parameter: ???) => {};
    
    performAction("dwdew"); // type error
    performAction(details.x.INFO_x) // valid
    

Answer №1

Revise

Upon revisiting the original post, it appears that the inquiry is not exactly in line with what was initially assumed. The function is intended to take a singular nested value as a parameter, rather than the entire object. While the comments on the question hint at potentially restricting the parameter's type to only xxx, there isn't a clear way to control its origin.

Despite this clarification, the initial response I provided could still prove beneficial to either the OP or others:

Suggested Revision

If you anticipate consistent formatting for the parameter structure, consider defining a type or interface for it:

interface Thing {
  a: {
    ROLE_a: string
  },
  b: {
    ROLE_b: string
  }
  // etc.
}

function doSomething(param: Thing) {
  // perform action
  console.log(param.a.ROLE_a); // no errors expected
}

For more adaptability, a combination of generics along with template literal types + key remapping can be utilized:

type Things<Prefix extends string, Keys extends string> = {
    [K in Keys]: {
        [T in K as `${Prefix}_${K}`]: string
    }
};

type ParamsType = Things<'ROLE', 'a' | 'b'>

function doSomething(param: ParamsType) {
    // perform action
    console.log(param.a.ROLE_a); // no errors expected
}

Access Playground Here

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 disable the camera on React-QR-Reader after receiving the result?

My experience with react-qr-reader has been smooth for scanning QR codes, however, I'm having trouble closing the camera after it's been opened. The LED indicator of the camera remains on even when not in use. I attempted using the getMedia func ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

What methods are available to keep a component in a fixed position on the window during certain scrolling intervals?

I need help creating a sidebar similar to the one on this Airbnb page. Does anyone have suggestions for how to make a component stay fixed until you scroll past a certain section of the page? I am working with functional React and Material-UI components, ...

When using react-admin with TypeScript, it is not possible to treat a namespace as a type

Encountering issues while adding files from the react-admin example demo, facing some errors: 'Cannot use namespace 'FilterProps' as a type.' Snippet of code: https://github.com/marmelab/react-admin/blob/master/examples/demo/src/orde ...

Referring to a component type causes a cycle of dependencies

I have a unique situation where I am using a single service to open multiple dialogs, some of which can trigger other dialogs through the same service. The dynamic dialog service from PrimeNg is being used to open a dialog component by Type<any>. Ho ...

Unexpected behavior with HashLocationStrategy

I am currently tackling a project in Angular2 using TypeScript, and I seem to be having trouble with the HashLocationStrategy. Despite following the instructions on how to override the LocationStrategy as laid out here, I can't seem to get it to work ...

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

Compilation of Zod record with predefined keys

I need to create a dictionary similar to a zod schema for an object with multiple keys that are already defined elsewhere, all sharing the same value type. Additionally, all keys must be required. const KeysSchema = z.enum(['a', 'b', &a ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

Error: Local variable remains undefined following an HTTP request

Whenever I make http calls, my goal is to store the received JSON data in a local variable within my component and then showcase it in the view. Service: getCases(){ return this.http.get('someUrl') .map((res: Response) => res.jso ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Navigating to a specific section upon clicking

Imagine a scenario where there is a landing page with a button. When the button is clicked, redirection to another page with multiple components occurs. Each component on this new page serves a different function. Additionally, the desired functionality in ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

How can I store an array of objects in a Couchbase database for a specific item without compromising the existing data?

Here is an example: { id:1, name:john, role:[ {name:boss, type:xyz}, {name:waiter, type:abc} ] } I am looking to append an array of objects to the existing "role" field without losing any other data. The new data should be added as individual ob ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

React's Redux persist is causing a duplication of requests being sent

I am currently utilizing redux-persist along with Redux Toolkit. I have observed a peculiar behavior where, upon changing the slice (RTK), a request is sent to the server. When using redux-persist without a persister, only one request is made as expected. ...

Challenge: Visual Studio 2015 MVC6 and Angular 2 compilation issue - Promise name not found

Initially, I've made sure to review the following sources: Issue 7052 in Angular's GitHub Issue 4902 in Angular's GitHub Typescript: Cannot find 'Promise' using ECMAScript 6 How to utilize ES6 Promises with Typescript? Visual ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...