What is the reason behind Typescript's objection to an object being incompatible with its assigned type?

While executing the TypeScript code below:

type dataType = {[key: string]: number} | {[key: string]: {[date: string]: number}} | {[key: string]: string;}


const myData1: dataType = {
  "name": "Eduardo",
  "city": "Miami",
  "state": "FL",
  "age": 22,
  "progress": {"2018": 67, "2019": 76, "2020": 89}
}

It results in an error stating that the object cannot be assigned to the type dataType even after specifying different types allowed inside the object explicitly. How can I properly allow multiple different types within an object?

This is the warning received:

Type '{ "name": string; "city": string; "state": string; "age": number; }' is not assignable to type 'dataType'.
  Type '{ "name": string; "city": string; "state": string; "age": number; }' is not assignable to type '{ [key: string]: string; }'.
    Property '"age"' is incompatible with index signature.
      Type 'number' is not assignable to type 'string'.

Your assistance will be much appreciated!

Answer №1

{ [key: string]: number }

This declaration specifies that all properties must be of type number.

{ [key: string]: { [date: string]: number } }

In this definition, it states that all properties must be objects with nested properties being numbers.

{ [key: string]: string; }

Here, the requirement is for all properties to be strings.

type valueType =
    | { [key: string]: number }
    | { [key: string]: { [date: string]: number } }
    | { [key: string]: string; }

This type indicates that it can only be one of the above possibilities - either all numbers, all strings, or all objects.

It does not allow mixing different property types within an object.

Therefore, the union should actually be at the property level, not at the object level as shown above.

type ValueType = {
  [key: string]: number | string | { [date: string]: number }
} 

Playground


If a more specific data structure is required, it can be defined using a single interface:

interface ValueType {
  name: string
  city: string
  state: string
  age: number
  progress: { [date: string]: number }
}

Playground

Answer №2

Your code's valueType is causing an issue because it specifies that the type will consist of key-value pairs with keys as strings and values being numbers, strings, or a specific type {[date: string]: number}}. What you actually need is a type where the keys are strings and the values can be either numbers or strings within the same object.

Here is a revised version:

type valueType = {[key: string]: number | string | { [date: string]: number }};

const myData1: valueType = {
  "name": "Eduardo",
  "city": "Miami",
  "state": "FL",
  "age": 22,
  "progress": {"2018": 67, "2019": 76, "2020": 89}
}

If you prefer to have fixed keys in your type:

type valueType = { name: string, city: string, state: string, age: number, progress: { [date: string]: number } };

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

Bypassing restrictions on AJAX requests across different domains

Can the AJAX cross domain request limitation be bypassed by loading a JS file containing $.getJSON from the same server (domain) as the URL in the AJAX request? For example, if there is a webservice on serverA.com that needs to be accessed from pages on va ...

How to extract the HTML content from specific text nodes using Javascript

I have a piece of HTML that looks like this: <div id="editable_phrase"> <span data-id="42">My</span> <span data-id="43">very</span> <span data-id="1">first</span> <span data-id="21">phrase< ...

Indicate the array as a tuple

Let's consider a scenario where there is an abstract class: type Pair = [string, number] abstract class AbstractPairClass { pairs: Pair[] } When attempting to implement this class as follows: class ConcretePairClass implements AbstractPairClass ...

Encountering a 401 Unauthorized error due to CORS origin issue when making a post request with HttpClient in Angular

Encountering an error when trying to upload data to my backend Firebase database. Here are the relevant code snippets: storeUsers(users: any[]){ return this.http.post('https://promise-90488.firebaseio.com/data.json', users); } appc ...

Struggling with implementing jquery Ajax and a php script to fetch information from a mysql database

I'm encountering issues with my current web app project in displaying a simple jpg image based on the selected radio button using jQuery AJAX along with a PHP script to interact with MySQL. Below is my ajax.js file: $('#selection').change( ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

Creating an HTTP POST request using JavaScript

Hi there, I'm currently working on an analytical project that focuses on delay tolerance for different applications. To gather user feedback, I need to develop a portable application using JavaScript. The goal is to send a request to the HTTP server c ...

What is the best way to create a personalized email form using javascript and reactjs without it opening in a new window?

I'm in the process of creating a contact section for my portfolio website that mimics an email interface. Instead of just providing a link, I want to include a complete form so visitors can easily reach out without needing to open a new window or exte ...

invoke two JavaScript functions without displaying any message

I'm facing an issue with Ajax as it's not displaying the message I intend to show. Let me elaborate. Within my PHP code, there is an input tag: <input type="submit" id="login_button_add" name="submit" value="Add" onclick="add_building(); sho ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Challenges with Converting Data Types in the R Programming Language

After transforming the vector a into a factor and then back to a numeric, why do the elements in a change? a = c(9, 10, 11, 12) a = as.factor(a) a > a [1] 9 10 11 12 Levels: 9 10 11 12 a = as.numeric(a) a > a [1] 1 2 3 4 ...

Enhanced JavaScript Autocompletion in Integrated Development Environments

What is the inner workings of Intellisense in IDEs like Webstorm and Eclipse for JavaScript? From which source do the suggestions originate? Is it possible to tweak the code to enhance the accuracy of the suggestions? https://i.sstatic.net/ZVBB3.png ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

What is the function of this.handleClick that is positioned on the LEFT side of the = operator?

I'm struggling to understand the usage of this in an ES6 constructor. Initially, I grasped the following concepts (see example below): - We utilize this.height = height; to introduce a new instance variable. - Adding a new instance method with cl ...

Exploring the concept of object inheritance in Angular 5 with Typescript

I'm facing a challenge related to inheritance while building my initial angular 5 application. The error message I encounter is: Property 'message' does not exist on type 'CouponEvent', as reported by the angular-cli. export class ...

Leveraging RouteProvider in Angular

I've encountered an issue while working with route provider. I'm trying to access a different path on my localhost:8080/showThemes.html page using the following method: <a ng-href="#/category/{{themes.theme}}"> <img class="imgCenter" ...

Switching between playing and pausing on multiple audio tracks

I have a collection of audio files with custom play/pause buttons that I've implemented. Each audio file is assigned a dynamic class, such as custom-aud-0, custom-aud-1, custom-aud-2, and so on... Here is my toggle function: togglePlay(c, index) { ...

How do I use jQuery to make a div appear when the previous one closes?

I've been experimenting with some code and it's gotten pretty lengthy. It works fine with just a few divs, but what if I need to implement this on 20 or more...? Is there a way to condense the code I've written? (I'm still new to jque ...