Obtain a union type using the `keyof typeof` syntax

Is there a way to retrieve the union or enum type from a typeof type in TypeScript?

For instance:

const myConfs: { [k: string]: (myArg: { name: string }) => string } = {
  'Hello': ({ name }) => `World from ${name}`,
  'Goodbye': ({ name }) => `World from ${name}`,
};
type MyKeys = keyof typeof myConfs;


// How can I make this throw an error?
const key: MyKeys = 'hello';

I attempted removing the type definition of myConfs, which worked initially, but it caused issues with the callback argument's type definition within the value field of myConfs.

Answer №1

One effective solution would be to utilize a factory function, which not only helps in resolving the issue at hand but also eliminates the need for redundant code.

function createConfs<T extends { [k: string]: (myArg: { name: string }) => string }>(confs: T) : T{
    return confs
}

const myConfs = createConfs({
  'Hello': ({ name }) => `World from ${name}`,
  'Goodbye': ({ name }) => `World from ${name}`,
})

type MyKeys = keyof typeof myConfs;

const key: MyKeys = 'hello';
// Type '"hello"' is not assignable to type '"Hello" | "Goodbye"'. Did you mean '"Hello"'?(2820)

Playground

Answer №2

There are numerous approaches to tackle this issue. Instead of allowing keys to be any string, use a mapped type to restrict it to the necessary set:

const keys = <const>["Apple", "Banana"];

type MyConfigurations = {
  [K in typeof keys[number]]: (argument: { itemName: K }) => string;
};

const myConfigs: MyConfigurations = {
  Apple: ({ itemName }) => `Delicious ${itemName}`,
  Banana: ({ itemName }) => `Ripe ${itemName}`
};

// This should trigger an error
const key: keyof MyConfigurations = "apple";

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

Oh no! It seems like the build script is missing in the NPM

https://i.stack.imgur.com/el7zM.jpg npm ERR! missing script: build; I find it strange, what could be causing this issue? Any suggestions? I have included the fullstack error with the package.json. Please also review the build.sh code below. Fullstack err ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Can a type be established that references a type parameter from a different line?

Exploring the Promise type with an illustration: interface Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

Is there a tool that can automatically arrange and resolve TypeScript dependencies, with or without the use of _references.ts file?

Currently, I am working on understanding the new workflow for "_references.ts" and I feel like there is something missing when it comes to using multiple files without external modules in order to produce correctly ordered ".js" code. To start with, I took ...

The type definition file for 'bson' could not be located. It appears to be missing from the program due to being the entry point for the implicit type library 'bson'

I recently set up a new Typescript/React project and encountered the following error in the tsconfig.json file: "Cannot find type definition file for 'bson'. The file is in the program because: Entry point for implicit type library 'bson&ap ...

Angular - Resolving the issue of 'property does not exist on type' in TypeScript

Currently, I am following a video tutorial which also has a text version. Despite copying the code exactly as shown in the tutorial, I encountered the following error: Error TS2339: Property 'getEmployees' does not exist on type 'Employ ...

Angular Karma encountered an error: TypeError - It is unable to read the property '_id' as it is undefined

Encountering an issue while testing with karma jasmine, the error message appears as... TypeError: Cannot read property '_id' of undefined This is the Component.ts file: import { Component, OnInit } from '@angular/core'; import { ApiSe ...

Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I a ...

Error Encountered When Trying to Import Mocha for Typescript Unit Testing

Here's a snippet of code for testing a Typescript project using mocha chai. The test case is currently empty. import {KafkaConsumer} from '../infrastructure/delivery/kafka/kafka-consumer'; import {expect} from 'chai'; import {descr ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts bootstrap: [AppComponent], declarations: [AppComponent], imports: [ CoreModule, HelloFrameworkModule, ], providers: [{ provide: Logger, useFactory: loggerProviderFunc(1), }] ...

Template reference does not connect to the ApexChart graphic

As a newcomer to ApexCharts.js, I am currently working on setting up a Vue3 app using Composition API along with the setup syntax. My goal is to reference the template ref of 'apexchart' so that I can later call the dataURI() function on it. I am ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

What is the reason for VS Code not displaying doc comments from type properties when suggesting descriptions and hover info for TypeScript objects?

The problem is clearly visible in the image below, as it pertains to the popup box in VSCode displaying type information and comments. Although the code works fine in VSCode, TypeScript Playground fails to display the comments properly, so it's best ...

Looking to organize an array of objects containing two string elements (countries) based on the country name using TypeScript or the Lodash library?

Below is an example of an array of objects I am working with: { countries: [{ "country_alpha2_code": "PW", "country_name": "PALAU" },{ "country_alpha2_code": "US&qu ...

Issue encountered with Typescript and Mongoose while operating within a Kubernetes cluster environment with Skaffold configuration

Here is the code snippet, const userSchema = new mongoose.Schema({ email: { type: String, required: true, }, password: { type: String, required: true, }, }); console.log(userSchema); userSchema.statics.build = (user: UserAttrs) =& ...

The TypeScript error arises when an element implicitly contains an 'any' type due to the inability to use an expression of type 'any' to index a specific type

Encountering an Issue: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ foo: string; bar: string; }'.ts(7053) Within the following code snippet: const CATEGORY_COLORS ...

What could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...