How can I specify the parameter type as "any object value" in TypeScript?

What is the proper way to annotate a parameter type as "any value of an object"?

class ExampleClass {

    private static readonly MODES = {
        DEVELOPMENT: 0,
        PRODUCTION: 1,
        TEST: 2
    }

    // Any Value of ExampleClass.MODES
    constructor(mode: MODE[?]) {

    }
}

In this scenario, the values 0, 1, 2 lose meaning if using an enum, but because enums cannot be used as class fields, we need to consider the case of "some value of an object."

Answer №1

Although Tomas made a good attempt, let's expand on the answer. To determine the type of values in typeof MODES, we can simply access it by using the types of all its keys.

type ValueOf<T> = T[keyof T];

// Avoiding widening the constant types to just `number`.
function asLiterals<T extends number, U extends { [n: string]: T }>(arg: U) {
    return arg;
}

class ExampleClass {

    private static readonly MODES = asLiterals({
        DEVELOPMENT: 0,
        PRODUCTION: 1,
        TEST: 2
    });

    // Any value within ExampleClass.MODES
    constructor(mode: ValueOf<typeof ExampleClass.MODES>) {

    }
}

Answer №2

In this particular case, you can utilize the type keyword:

type myType = 'DEVELOPMENT' | 'PRODUCTION' | 'TEST'
class someClass {
  // Accepts any value of myType
  constructor(mode: myType ) { }    
}

For more complex scenarios, refer to the TypeScript documentation snippet below, where K extends keyof T ensures only specified object values are passed as function arguments:

function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
  return names.map(n => o[n]);
}

interface Person {
    name: string;
    age: number;
}
let person: Person = {
    name: 'Jarid',
    age: 35
};
let strings: string[] = pluck(person, ['name']); // valid, returns string[]

This utility service can be used universally across multiple constructors where type safety is desired.

You can also encapsulate secure values in a separate class and use keyof directly:

class A  {
    prop1: 1;
    prop2: 2;
}

class TestClass {
    constructor(key: keyof A) {

    }
}

let tc1 = new TestClass('prop1')
let tc2 = new TestClass('whoops') // Results in an error

If you are looking for something similar to valueof rather than keyof, enums and types should be your focus.

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

Setting an attribute on a custom component that is dynamically created within an Angular application

I am working with a custom library component called <my-icon>. To display the icon, I need to specify the property [name] like this: <my-icon [name]='warning'></my-icon> Currently, I am dynamically creating these icons in Type ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Setting IDPs to an "enabled" state programmatically with AWS CDK is a powerful feature that allows for seamless management of

I have successfully set up Facebook and Google IDPs in my User Pool, but they remain in a 'disabled' state after running CDK deploy. I have to manually go into the UI and click on enabled for them to work as expected. How can I programmatically e ...

Angular 4 - Seeking clarification on the usage of *ngComponentOutlet

When using *ngComponentOutlet, the following code snippets are employed to handle the displaying: Below is a snippet of functional code: this.displayComponent({ 'objects':[ {component: ToDisplayAComponent, expanded: fals ...

Can we determine the type signature of useCallback for an event handler by inference?

Currently, I am working with TypeScript and React to implement a callback function using an arrow function on a Material UI <Select> component: import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import ...

The error message related to TupleUnion in TypeScript is indicating that the depth of type instantiation may be too deep and could

Recently, I've been delving into a TypeScript utility type known as TupleUnion. This useful type came to my attention through a fascinating Twitter post, and I've observed it being utilized in various Stack Overflow solutions. Here's how the ...

Connect AngularFire to a specific object

I'm facing an issue with my Users.class where I need it to automatically map or bind after fetching data from Firebase. I've been trying to search for the right term but haven't found any information yet. import { Component, OnInit } from & ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Guide on creating a custom type for an object utilizing an enum framework

Enumerating my shortcuts: export enum Hotkey { MARK_IN = 'markIn', MARK_OUT = 'markOut', GO_TO_MARK_IN = 'goToMarkIn', GO_TO_MARK_OUT = 'goToMarkOut' } I am now looking to define a type for a JSON ob ...

I have attempted numerous methods, but the TypeScript object remains potentially undefined

My current code involves using canvas to capture the cropped image. Below is the function that handles this process: export const getCroppedImg = ( image: HTMLImageElement, crop: Crop, fileName: string ): Promise<Blob> => { let canvas: HTM ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

Why won't my boolean value in the Angular service reflect in the HTML code?

For my project, I am utilizing a stepper and I need to display or hide a div based on the selected product. However, I am encountering an issue where the HTML isn't updating when I try to call the done() function. .service public beneficiary = true; ...

Creating Custom Type Guards for Literal Types in Typescript: Is It Possible?

Note: I am new to using typescript. Before asking this question, I made sure to go through the documentation on advanced types and type guards. Additionally, I looked into several related questions on Stack Overflow such as user defined type guards [typesc ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

Why does TypeScript include a question mark next to the argument when GraphQL specifies it as nullable true?

// image.entity.ts import { Field, ObjectType } from '@nestjs/graphql'; import { Column, DeleteDateColumn, Entity, PrimaryGeneratedColumn, } from 'typeorm'; @ObjectType() @Entity() export class ImageEntity { @PrimaryGenerate ...

What is the purpose of specifying the props type when providing a generic type to a React functional component?

When utilizing the @typescript-eslint/typedef rule to enforce type definitions on parameters, I encountered an issue with generically typing a React.FC: export const Address: React.FunctionComponent<Props> = (props) => ( An error was thrown st ...