What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt:

export const cityToZone: { [city: string]: Array<string> } = [

    {city:'New York', ['zoneA','ZoneB']}
]

However, I am encountering an error message:

(TS) Type '{ city: string; ['zoneA','ZoneB']: any; }' is not assignable to type 'string[]'. Object literal may only specify known properties, and 'city' does not exist in type 'string[]'.

As someone new to typescript, I'm struggling to identify the issue here.

Answer №1

Welcome to the TypeScript community!

Let's delve into what is happening here:Array<string> (also written as string[]) represents a structure like ['a', 'b', 'c']. It differs from the structure you provided:

[{city:'New York', ['zoneA','ZoneB']}]
, hence the failure.

To resolve this issue, I suggest changing the type from Array<string> to City[] (or Array<City>). The City type should be defined as below:

type City = {
  city: string;
  zones: string[];
};

You can then utilize it in this manner:

export const cityToZone: City[] = [{
  city: 'New York', 
  zones: ['zoneA','ZoneB']
}];

For further enhancement, incorporate union types for city names and zones as shown below:

type CityName = 'New York' | 'Denver' | 'Washington, D.C.'; // etc
type ZoneName = 'Zone 1' | 'Zone 2' | 'Zone 3'; // etc

This will modify your City type to look like this:

type City = {
  city: CityName;
  zones: ZoneName[];
}

Update: Feel free to experiment with this on CodeSandbox: https://codesandbox.io/s/typescript-j90gi?fontsize=14&hidenavigation=1&theme=dark

Update 2 (mapping question): If your city names are unique, consider restructuring your data into

type CityMap = Record<CityName, ZoneName[]>;

and implement it like so:

export const cityToZone: CityMap = {
  'New York': ['zoneA', 'zoneB'],
  'Denver': ['zoneC', 'zoneD'],
};

This approach allows you to retrieve zones by city name in constant time (O(1))

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

Challenge with sharing an array from a different component in Angular using @Input()

Recently, I started learning Angular and decided to create a basic blog application. While trying to retrieve a property from another component using the @Input() decorator, I encountered an issue specifically related to arrays. In a post-list-item compone ...

Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet: enum Status { SUCCESS = 'success', FAILED = 'fa ...

Incorporating regular expressions to extract a specific string from a URL is a requirement

Can anyone assist with extracting a specific string using regex in TypeScript? I have the following URL: https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132 I ...

How to incorporate a popup modal in your project and where should you place the DialogService constructor

Currently, I am in the process of developing a CRUD ASP.NET Core application using Angular 2 and Typescript. Prior to incorporating a popup feature, this was my output: https://i.stack.imgur.com/vHvCC.png My current task involves placing the "Insert or e ...

Angular 6 introduces a new component with cascading comboboxes for easier data organization

In my Angular 6 project, I have successfully implemented a shared component called country-state. It is functioning perfectly. VIEW MY PERFECT WORKING EXAMPLE However, upon dividing the country-state component into separate country and state components, ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Having trouble with routerLink in your custom library while using Angular 4?

In my Angular 4 project, I have developed a custom sidebar library and integrated it into the main project. My current issue is that I want to provide the option for users to "open in new tab/window" from the browser's context menu without having the ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Angular 2 error: "unknown element" issue persists despite exhausting all attempted solutions

Here's a typical scenario where I attempt to incorporate a component from another module : External component : import { Component, ViewEncapsulation, ElementRef, ViewChild, Input, Output, EventEmitter } from '@angular/core'; declare ...

The onSubmit function in Formik fails to execute if there are no input values present

I am currently working on building a form using Next.js, TypeScript, and the Formik + Yup libraries. I've encountered two scenarios: one where an input field is visible and Formik captures the value, and another where the input is not visible and the ...

Enhance Your NestJS Experience: Using Interceptors for Mapping and Error Handling

I'm looking for a NestJS interceptor that can log requests in all scenarios, including both successful executions and errors. Below is an example implementation: public intercept(context: ExecutionContext, next: CallHandler): Observable<any> { ...

Ionic app on mobile device experiencing issue with Autocomplete feature not filtering correctly in Angular

I am facing an issue with my autocomplete form. It works perfectly fine locally, but once compiled to a PWA, the data filtering feature stops functioning properly. The API is returning a JSON array response as expected. var modify = function (term) ...

Issue with exporting member in VS Code but not in console

I currently have a NestJS project (project A) with one module that utilizes the @nestjs/typeorm and typeorm packages. In my other NestJS project (project B), I plan to use this module. However, there is a potential issue. Project B contains entities that ...

Ways to address the issue of duplicated names in input fields

Currently, I am utilizing a React Hook Form hook known as useFieldsArray. This hook is responsible for rendering an array of fields, each containing an object with the data that will be transmitted via the input. One interesting feature is the ability to ...

Expanding the range of colors in the palette leads to the error message: "Object is possibly 'undefined'. TS2532"

I am currently exploring the possibility of adding new custom colors to material-ui palette (I am aware that version 4.1 will include this feature, but it is a bit far off in the future). As I am relatively new to typescript, I am finding it challenging t ...

How can I implement a user notification service using rxjs within Angular?

As a newcomer to reactive programming, I am exploring ways to create an Angular service that can present notifications to the user. Check out what I have accomplished so far: https://stackblitz.com/edit/angular-rxjs-notifications?file=app%2Fapp.component. ...

Can someone provide guidance on utilizing the map function to iterate through intricate components in TypeScript?

I am facing a challenge while trying to iterate through a complex object containing 'inner objects'. When using the map function, I can only access one level below. How can I utilize map and TypeScript to loop through multiple levels below? Whene ...

Is it possible for a class that implements an interface to have additional fields not defined in the parent interface?

Looking at the code snippet below, my aim is to ensure that all classes which implement InterfaceParent must have a method called add that takes an instance of either InterfaceParent or its implementing class as input and returns an instance of InterfacePa ...

What is the best way to include a Web Service within an export variable in Angular 2 using TypeScript?

Is there a way to incorporate JSON data retrieved from the server into the export var HEROES: Hero[ ] function? Here is the link: https://angular.io/resources/live-examples/toh-5/ts/eplnkr.html In app/mock-heroes.ts, you will find the following data, im ...

Utilize Typescript compiler to identify mistakes during object property access using square brackets

Is it possible to configure the Typescript compiler to identify errors when accessing object properties using square brackets? I have inherited a codebase where object property access is predominantly done with square brackets (obj['myProp'] ins ...