Creating a map object in Typescript with limited enumerable properties

Is there a way to restrict the values of an object map to a certain type while still being able to enumerate its keys?

Consider the following:

const obj = {
  a: 'a',
  b: 'b'
}

type Obj = typeof obj

const obj2: Obj

In this case, obj2 is typed with properties a and b.

However, if we want to restrict the properties of obj to be only strings, we can do the following:

const obj: {[name: string]: string} = {
  a: 'a',
  b: 'b'
}

type Obj = typeof obj

const obj2: Obj

Now, obj2 has no typed props and is limited to any indexed string property. But what if we want it to have only a and b props without explicitly enumerating their key types?

const obj: {[name in ('a' | 'b')]: string} = {
  a: 'a',
  b: 'b'
}

type Obj = typeof obj

const obj2: Obj

Is there a simpler way to achieve this?

Answer №1

Essentially, no, it is not feasible. It seems a more practical approach would be to specify a restricted type and then convert it to an indexer type when necessary:

type Indexer = {[name: string]: string};
type Obj = {a: string, b: string};
obj: Obj = {a: 'a', b: 'b'}

// Utilizing Lodash map
_.map(<Indexer> obj, (val, key) => {})

Please Note:

If you are wary of using Indexers due to potential type safety issues, there is an ongoing discussion regarding this topic in the following thread

If type safety is not a concern for you, you can simply define your type like so:

type Obj = {a: string, b: string, [name: string]: string}}

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

Determining function return type based on argument type

In the code snippet provided, the function useSearchResults (a React hook) initializes the state based on the argument. The config.state can be any value defined in SearchResultsState or a function that returns a value defined in SearchResultsState. The r ...

Utilizing React Component Inheritance for Utilizing both Parent and Child Methods

Exploring Options After developing a fully functional component with state, props, and methods, I encountered an issue where the component needed to behave differently based on the operating system (iOS or Android). Initially, I used conditional statement ...

Beginning selenium web-driver with TypeScript - a simple guide

Currently, I am embarking on a UI Automation project utilizing Selenium and typeScript. I would greatly appreciate any insights on how to proceed with this endeavor. My previous experience involves working with Selenium WebDriver in Java. I have successf ...

Tips for setting up various mock services for testing an Angular 2 component

I am working with two Mock services: @Injectable() class UserRegistrationServiceMock { registerBasicDetails(details: UserRegistrationDetails) { let response: UserRegistrationResponse = new UserRegistrationResponse(); response.success = ...

Angular ngx-translate: Responding to language change event

Is it possible to detect the change in the "current language" using the ngx-translate library? Which JavaScript event should I use to accomplish this task? To clarify, please refer to this straightforward example: https://stackblitz.com/edit/github-yvbmgu ...

Dividing a collection of URLs into smaller chunks for efficient fetching in Angular2 using RxJS

Currently, I am using Angular 2.4.8 to fetch a collection of URLs (dozens of them) all at once. However, the server often struggles to handle so many requests simultaneously. Here is the current code snippet: let collectionsRequests = Array.from(collectio ...

Utilizing Angular 2 to Access APIs with Basic Security Authentication

I am attempting to make a call to an HTTP method implemented with ASP Web API from an Angular 2 client. However, I am encountering the following error: OPTIONS 401 (Unauthorized) XMLHttpRequest cannot load . The response to the preflight request does no ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Utilizing Angular 2's NgFor directive in SVG Elements

I want to use ngFor to draw an SVG Element that consists of lines. I am struggling with the implementation and need some help fixing the code. Here is what I have so far: my-component.js: import {Component} from 'angular2/core'; @Component({ ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

The 'performance' property is absent in the 'FirebaseApp' type, which is necessary in the 'App' type

Encountering an issue during a fresh installation of Angular 7.2 and Firebase, specifically getting this error: ERROR in node_modules/@angular/fire/firebase.app.module.d.ts(17,22): error TS2420: Class 'FirebaseApp' incorrectly implements interfa ...

Determine data type using the generic type of a related property in Typescript

I am seeking a method to specify the type of a property based on the generic type of another property within the same context. For instance, consider the following: type Person = { id: number; name: string; } type Select<Value=unknown> = (props ...

Leveraging Angular 4 with Firebase to extract data from a database snapshot

My dilemma lies in retrieving data from a Firebase DB, as I seem to be facing difficulties. Specifically, the use of the "this" operator within the snapshot function is causing issues (highlighted by this.authState.prenom = snapshot.val().prenom) If I att ...

Displaying webpack errors within gulp is a simple process

My TypeScript project utilizes webpack for transpilation, and gulp for managing build tasks. Let's consider this simple task to illustrate my query: var webpack = require('webpack'); var webpackStream = require("webpack-stream"); gulp.task ...

Unlock the potential of ng-for to dynamically generate input boxes and checkboxes!

In this Angular application, my requirement is to repeat the elements inside a div based on the number entered in an input box (record.accountRoles). <!-- Input Box --> <div class="form-group"> <label for="name">Enter the number of a ...

Issue: Unable to call method "call" as the model "Model" has not been initialized within a Sequelize instance. Kindly ensure that "Model" is added to a Sequelize instance before attempting to use the "call" method

Author.ts import {Table, Model, Column, DataType} from 'sequelize-typescript' @Table export class Author extends Model<Author> { constructor(){ super(); } @Column(DataType.STRING) fname: string @Column(DataType.STRING) lname: strin ...

Specialized Character Formats in TypeScript

In my quest to enhance the clarity in distinguishing different types of strings within my program - such as absolute paths and relative paths, I am seeking a solution that ensures functions can only take or return specific types without errors. Consider t ...

Utilizing TypeScript: Implementing a class within an object with explicit typing

I'm struggling with explicitly assigning a type in TypeScript from a class nested within an object (essentially a namespace): let obj = { hello: class { constructor: function () { console.log('hi'); } } } ...

What is the correct way to utilize the mapState function within a TypeScript environment while implementing Vuex?

In my Vue.js project integrated with Vuex, I am using Typescript syntax. While trying to use the mapState method as computed in my .ts file, I encountered a syntax error. Currently, I am following the suggested syntax for computed function in the documenta ...

Declaration of dependencies for NestJS must include dependencies of dependencies

I'm encountering an issue where NestJS is not automatically resolving dependencies-of-dependencies: I have created an AWSModule which is a simple link to Amazon AWS with only a dependency on the ConfigService: @Module({ imports: [ConfigModule], ...