When using TypeScript, a custom property name within a type declaration must explicitly point to a predefined symbol

An error has occurred in ...component.ts (..,..): A computed property name in a type literal must directly refer to a built-in symbol. Error message: Cannot find name 'any'.

I am seeking an object that contains strings that have another string, like this:

{ abc: 'xyz' }

This is what I attempted:

foo: { [string]: string };

Answer №1

A specific name is necessary for the computed value:

foo: { [bar: string]: string };

Answer №2

Encountered a similar issue post-building. The challenges were related to utilizing numbers and enum values as keys in objects. Here's some guidance for those facing this in the future.

Enums Used as Keys

export enum MyEnum {
  one = 'stringOne',
  two = 'stringTwo',
}

export const someMap = {
  [ MyEnum.one ]: 'valueOne',
  [ MyEnum.two ]: 'valueTwo',
};

Upon compilation, someMap will be transformed into a type resembling...

export declare const someMap: {
  [ MyEnum.one ]: string;
  [ MyEnum.two ]: string;
};

Note that the keys remain as enum values and not strings, which typescript/angular might not approve of because it anticipates something like...

export declare const someMap: {
  [ x: string ]: string;
};

To resolve this, consider...

1) Explicitly Define Type for someMap

export interface ForceStringType {
  [product: string]: string;
}
export const someMap: ForceStringType = {
  [ MyEnum.one ]: 'valueOne',
  [ MyEnum.two ]: 'valueTwo',
};

2) Use string Type for Keys in someMap

export const someMap: ForceStringType = {
  [ MyEnum.one as string ]: 'valueOne',
    [ MyEnum.two as string ]: 'valueTwo',
};

Numbers Employed as Keys

const CONSTANT_ONE = 123;
const CONSTANT_TWO = 321;

export const someMap = {
  [ CONSTANT_ONE ]: 'valueOne',
  [ CONSTANT_TWO ]: 'valueTwo',
};

Post-transformation, someMap will manifest as...

export declare const someMap: {
  [ CONSTANT_ONE ]: string;
  [ CONSTANT_TWO ]: string;
};

The keys persist as constants/numbers instead of strings, prompting typescript/angular to expect...

export declare const someMap: {
  [ x: string ]: string;
};

A potential solution is...

Convert Numbers to Strings for Key Assignment in someMap

export declare const someMap: {
  [ `${CONSTANT_ONE}` ]: string;
  [ `${CONSTANT_TWO}` ]: string;
};

Note: Accessing values from someMap using constants/numbers as keys should function correctly as typescript automatically converts them to strings. However, maintaining consistency by explicitly converting to strings is advisable.

const valueOne: string = someMap[ CONSTANT_ONE ];
// vs
const valueOne: string = someMap[ `${CONSTANT_ONE}` ];

Answer №3

The existing solution may encounter difficulties when the key type is derived from a generic source. In such cases, the in operator becomes essential:

type WithKey<K extends string | number | symbol> = {
    [k in K]: boolean
}

Source of idea.

Answer №4

When working with a Vue component, I encountered an issue related to incorrectly binding class names:

Check out the Vue documentation for more information.

<script lang="ts">
import { defineComponent } from '@vue/composition-api'

export default defineComponent({
  props: {
    className: String,
  },

  setup() {
    const isModified = computed<boolean>(() => true)

    return {
      isModified,
    }

<template>
  <!-- Incorrect way -->
  <div 
    class="static-class" 
    :class="{ [className]: true, 'static-class--modified': isModified }]">
  </div>

  <!-- Correct way -->
  <div 
    class="static-class" 
    :class="[className, { 'static-class--modified': isModified }]">
  </div>
</template>

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

Validation error from Express-validator may result in TypeScript error: the request.query object could potentially be undefined

Recently, as I was developing a Node.js app using express, I decided to enhance it with express-validator. Despite being new to express-validator, the warnings it generated perplexed me due to its lack of detailed documentation. To illustrate my point, he ...

Functions outside of the render method cannot access the props or state using this.props or this.state

Just starting out with react. I've encountered an issue where a prop used in a function outside the render is coming up as undefined, and trying to use it to set a state value isn't working either. I've researched this problem and found va ...

Replacing a push operation in JavaScript with a splice operation

Upon entering a screen, 5 promises are automatically loaded using promise.all. The issue is that they are executed in a random order, and within each function, I use a push to store the information. The problem arises when I need to change the push to a s ...

Utilizing TypeScript to define React interfaces

How can I effectively utilize two interfaces for the same object? For instance: interface interfaceOne { id: string color: string } interface interfaceTwo { id: string numb: number } I have an Item component that is designed to receive an item ob ...

What is the best way to provide inputs to a personalized validation function?

I am seeking a solution to pass an array of prefix strings to my custom validator in order to validate that the value begins with one of the specified prefixes. Below is the code snippet for my current validator: @ValidatorConstraint({ name: 'prefixVa ...

Explore the titles provided by Wikipedia

Hi there, I'm fairly new to Angular and trying to work with the Wikipedia API. However, I seem to be having trouble getting 4 titles from the API. Here's an example URL for one of the titles: https://en.wikipedia.org/w/api.php?action=query&pr ...

Is it considered bad form to utilize nearly identical for loops in two separate instances within Angular 6?

I am working on creating two lists for a roster. The first list will display the current members of this year, while the second list will show if individuals have been excused for this year. After analyzing my code, I realized that I am using two identic ...

Why doesn't TypeScript automatically determine the prop type when Generics are used?

Below is the code snippet: interface MyInterface { a: { b: { c: "c"; }; }; } type ParentProps = keyof MyInterface type ChildProps<ParentProp extends ParentProps> = keyof MyInterface[ParentProp] type GrandChildType< ...

Can a npm package be created using only typescript?

I am working on a project that is specifically tailored for use with TypeScript projects, and I want the code inspection to lead to the actual lines of TypeScript code instead of a definition file. However, I am struggling to set up an npm project to achi ...

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

Is there a way to implement hover behavior for a Material-UI Button within a ButtonGroup component?

When using MUI v5, I am encountering an issue where the first button in the code provided is only half working. The button is initially colored red (both the border and text), however, upon hovering over it, the color of the border changes to blue. This is ...

Tips for simulating or monitoring an external function without an object using Typescript 2 and Jasmine 2 within an Angular 4 application

In order to verify if a function called haveBeenCalledWith() includes the necessary parameters, I am seeking to validate the correctness of my call without actually executing the real methods. I have experimented with multiple solutions sourced from vario ...

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

When logging `self`, the output field is present; however, attempting to log `self.output` results in

I've encountered a strange issue. When I use console.log(self) to log the variable, it shows that the output key is set and contains all the values. However, if I try to log console.log(self.output), it returns undefined. Does anyone know why this is ...

Guide to writing a unit test for a parameter decorator in NestJs

I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controll ...

What is the best way to ensure that GCM push notifications are still received even when the app is closed or the

Currently, I'm in the process of developing an application using Ionic 2 that requires push notifications to be received. In certain scenarios, such as when the app is force-stopped on Android or when the device is turned off, push notifications are ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Encountering a VersionError with Mongoose and MongoDB: Unable to find a document matching the ID "60bf5b73de309f1a30fe88a2" and version 10, with modified paths including "likes"

While developing my fullstack application (a Facebook clone), I encountered an error in my server that I am struggling to resolve. The technologies I am using include node.js, express, MongoDB, Mongoose, and TypeScript. The error occurred during the devel ...