TS2559: Type 'String' lacks any common properties with type 'object'

When working with TypeScript, I encountered an issue with a map defined as shown below that is intended to accept (key, value) pairs of (string, anything).

let map = new Map<String, Object>()

Upon attempting to insert a (key, value) pair into the map using code like this:

map.set("name", "someName");

I encountered the error

TS2559: Type  string  has no properties in common with type  Object
, indicating that String does not inherit from Object in this case.

What would be the optimal approach to handle this situation in TypeScript? Interestingly, such operations are successful in Java.

Answer №1

String and Object types point to values stored in the "heap", similar to Java. However, in TypeScript, string literals are typed as string. The type String refers to objects, while string refers to "primitive values". For more information, MDN has a detailed article published here.

The definition of Object is as follows (you may not understand its signature, but don't worry about it - it's not relevant):

interface Object {
    constructor: Function;
    toString(): string;
    toLocaleString(): string;
    valueOf(): Object;
    hasOwnProperty(v: PropertyKey): boolean;
    isPrototypeOf(v: Object): boolean;
    propertyIsEnumerable(v: PropertyKey): boolean;
}

(Assuming you are familiar with Java's interface, I will skip explaining what an interface is)

In contrast, the type string has the following members:

  • An index signature of number which is similar to the charAt(int) method in Java,
  • Symbol.iterator, mostly identical to CharSequence's codePoint method in Java,
  • and various methods named after strings

TypeScript uses "structural typing", which differs from Java's "nominal typing" system. A key distinction between these systems is that structural typing assesses sub-typing based on the type's properties. In other words, in TypeScript, Hello and Hi are considered the same type, unlike in Java:

interface Hello {}

interface Hi {}

const hello: Hello = {};
// no compile errors
const hi: Hi = hello;

TypeScript evaluates the intersection set of properties to determine if a value can be assigned or passed. However, Object and string have no common properties at all! TypeScript raises an error to indicate this mismatch.

To resolve this, you can change String to string as suggested by other users.

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

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

Change the type declaration of a list of elements to a list containing those elements organized within a container - Array<Wrapper<T>>

Is there a way to convert a plain array into an array of wrapped items in JavaScript? declare type MyGenericArray = [number, string, boolean] declare type WrappedGeneraicArray = Wrap<MyGenericArray> // WrappedGeneraicArr ...

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

Using TypeScript with Styled Components .attrs

I'm a bit perplexed about using the .attrs() function in conjunction with TypeScript. Let's consider the code snippet below: BottleBar.tsx: interface IBottleComponentProps { fill?: boolean } const BottleComponent = styled.div.attrs<IBottl ...

Ensure that the objection model aligns with the TypeScript interface requirements

I am currently working on implementing an API using express, objection.js, and TypeScript. I found a lot of inspiration from this repository: https://github.com/HappyZombies/brackette-alpha/tree/master/server/src Similar to the creator, I aim to have var ...

Apply a spread of nested elements onto another spread

I am working with an array containing last names of Persons and need to populate new entries. However, I only have the last names and not the full Person objects. How can I address this issue? type Person = { name: string, lastName: string, age: ...

Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code. ACC.payDirect = { _autoload ...

Guide on importing npm packages without TypeScript definitions while still enabling IDE to provide intelligent code completion features

I am currently utilizing an npm package that lacks type definitions for TypeScript. Specifically, I'm working with the react-google-maps library. Following their recommended approach, I have imported the following components from the package: import ...

Jest - managing parent class methods during unit tests

The code snippet provided demonstrates a class called First extending TelemetryFramework with specific props and states, containing a method named getData. This method retrieves confidential data and logs telemetry information. However, running unit tests ...

Using JSON to convert data into a Python dictionary

Here is some data I have: { "dataFrame": "AB3hqqqpVVVOAAA=", "decrypted": true, "fcnt": 3, "id": 1480528200533, "port": 5, "rssi": -116, "sf_used": 10, "snr": -8.5, "timestamp": "2016-11-30T17:50:00.533Z" }, { ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

What is the method for defining a monkey patched class in a TypeScript declarations file?

Let's say there is a class called X: class X { constructor(); performAction(): void; } Now, we have another class named Y where we want to include an object of class X as a property: class Y { xProperty: X; } How do we go about defining ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

What are the appropriate Typescript typings for React Components that have the ability to return a string or their child components directly?

What are the suitable types for a React Component that can also output a string or directly its children, in addition to a JSX.Element? For example: type PropsStringExample = Readonly<{ returnString: boolean; }>; type PropsChildrenExample = Readon ...

What is the purpose of `{ _?:never }` in programming?

I've been going through some TypeScript code and I stumbled upon a question. In the following snippet: type LiteralUnion<T extends U, U extends Primitive> = | T | (U & { _?: never }); Can anyone explain what LiteralUnion does and clarif ...

Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests. I want to implement error handling by using the Ha ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...