Exploring Objects in TypeScript/JavaScript

class ResistorColor {
  private colorOptions: string[]
    
  public colors = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colorOptions: string[]) {
    
    if( colorOptions.length > 2)
    {
      for( let key in this.colors)
      {
        if (this.colors[key].indexOf(colorOptions[0]) !== -1) 
        {
          return key;
        }
      }
    }

    this.colorOptions = colorOptions
    
  }
}

The goal is to check if the user-input color exists in the object colors.

I found inspiration from this discussion on Stack Overflow: Find a value in a JavaScript object

I encountered an error saying cannot find name key. I am using an online TypeScript editor.

Please help me understand what I am doing incorrectly here.

Answer №1

Take a look at the response from @Owl, it addresses the other issues present in your code as well.

The variable key is not defined within your loop. You should define it like this:

for (const key in this.colorValues) {
  ...
}

Instead of using a for-in loop, I recommend using the following solution to avoid receiving prototype properties:

for (const key of Object.keys(this.colorValues)) {
  ...
}

If you only need the values from the colorValues object and not the keys, you can simplify your loop like this:

for (const color of Object.values(this.colorValues)) {
  ...
}

Answer №2

The error message "cannot find name key" has been resolved by @MrCodingB

A more elegant way to present this solution:

class ResistorColor {
  private colors: string[]
    
  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {
    
    const colorValues = Object.keys(this.colorValues);
    
    const isValid = colors.every(c => colorValues.includes(c));
    
    if (isValid) {
      this.colors = colors
    } else {
      throw new Error("Invalid Color(s)");
    }
  }
}

const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has the correct colors");

const resistorColor2 = new ResistorColor(["black", "brown", "gold"]); // throws error
console.log("resistorColor2 has the correct colors");

Typescript playground


You can also display any incorrect colors by utilizing the .filter() method

class ResistorColor {
  private colors: string[]
    
  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {
    
    const colorValues = Object.keys(this.colorValues);
    const invalidColors = colors.filter(c => !colorValues.includes(c));

    if (invalidColors.length === 0) {
      this.colors = colors
    } else {
      throw new Error(`Invalid Color -> ${invalidColors.join(", ")}`);
    }
  }
}

const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has the correct colors");

const resistorColor2 = new ResistorColor(["black", "brown", "gold", "foo"]); // throws error "Invalid Color -> gold, foo"

Typescript playground

Answer №3

To avoid runtime errors, consider using stricter types during compilation. By defining a type that only accepts specific string literal color names and enforcing a minimum length on the colors array with tuple types, you can catch these errors early.

Is it possible that this.colorValues is essentially an enum?

enum COLOR_VALUES {
    black = 0,
    brown = 1,
    red = 2,
    orange = 3,
    yellow = 4,
    green = 5,
    blue = 6,
    violet = 7,
    grey = 8,
    white = 9
}

type ColorNames = keyof typeof COLOR_VALUES;

class ResistorColor {

    // Accepts two or more colors
    constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
    }
}

Now the constructor can only be called with valid arguments.

const a = new ResistorColor(["black", "blue"]); // ok
const b = new ResistorColor(["black", "blue", "red"]); // ok
const c = new ResistorColor(["black"]); // error: Source has 1 element(s) but target requires 2.
const d = new ResistorColor(["white", "cyan"]); // error: Type 'cyan' is not assignable to type 

Typescript Playground Link

If this.colorValues is an instance variable, consider initializing it outside the class for easier referencing using typeof.

const initialValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

type ColorNames = keyof typeof initialValues;

class ResistorColor {

    public colorValues = initialValues;

    // Accepts two or more colors
    constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
    }
}

Typescript Playground Link

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

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

The input element doesn't show the value when generated by an Angular Directive

I have developed a custom directive that enables me to replicate some HTML with an input field. However, the issue arises when the input is rendered, as the value field gets populated with the value from the scope but does not appear on the screen. This p ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

"Utilize d3.js to selectively filter through a nested array of objects based on specific object

I have collected a dataset of meteorite landings and organized the data into four keys based on type: var dataByType = d3.nest() .key(function(d) { return d.rectype; }) .entries(dataset); // original dataset You can see the result ...

Typescript integration in Next.js

When deploying a Next.js project with TypeScript, sometimes errors occur that do not show up during development. Here is an example of such an error: 13:09:26 Failed to compile. 13:09:26 ./node_modules/next/dist/build/webpack/plugins/pages-manifest ...

Implement jQuery Tabs in Brackets software to enhance user experience

My Adobe Creative Cloud subscription is expiring soon, and I am considering switching to Brackets, an open-source code editor developed by Adobe. However, I am facing some difficulties adding jQuery tabs to my HTML documents. I downloaded the 1.10.4 zip f ...

Issues with unresponsive buttons in AngularJs

In creating a basic registration page, I encountered a strange issue with the button functionality. Whenever I attempt to submit the form, an error should be logged to the console. However, the buttons on the registration page appear to be inactive - it se ...

Exploring the functionality of CodePen's code editor in relation to developing a 2D shooting game

Recently, I created a straightforward 2D shooter game with all the code neatly organized in a single HTML file: (file_gist). When I tested the game in my chrome browser, everything worked flawlessly according to my intentions. However, upon transferring th ...

Strategies for excluding a union type based on the value of a field

I have this specific type structure (derived from a third-party library): type StackActionType = { type: 'REPLACE'; payload: { name: string; key?: string | undefined; params?: object; }; source?: string; ...

Testing React components by writing unit tests to locate specific elements within the component

Seeking assistance for a challenge I'm facing with writing unit tests in React. I'm trying to verify the existence of an action button and link button within a component. Below is the code snippet for the component, which renders a child componen ...

Using React.ReactNode as an argument in Storybook

This is a unique button component type that I have created import React from 'react' export type ButtonProps = { label: string; color?:'primary' | 'secondary' | 'tertiary'; size?:'mobile' | 'tabl ...

Implementing a design aesthetic to installed React components

After downloading a react multiselect component created by an individual, I installed it using npm install .... and incorporated the component in my react code with <MultiSelect .../>. The dropdown checkbox 'menu' is designed to allow users ...

What is the process for including a callback in an angular resource?

In my current setup, I have a view that displays a list of items: <li ng-repeat="item in items">{{item.name}}</li> The associated service code is as follows: angular.module('itemService', ['ngResource']). factory(&apo ...

Stop JQuery from executing when an error is caught

Once the document is ready, I have configured: $.ajaxSetup({ "error": function (XMLHttpRequest, textStatus, errorThrown) { if(XMLHttpRequest.status == 403) { display_modal( 'Please login to continue.', &ap ...

access the ckeditor within the frame

I have a CKEditor in a frame and am experiencing an issue. When I try to console log from the browser, it won't work until I inspect near the frame and perform the console log again. [This is the CKEditor] https://i.stack.imgur.com/fWGzj.png The q ...

Building an effective HTTP request for an API using Node.js and Express

As a newcomer to HTTP, I'm venturing into making my first HTTP request. Below is the API reference: https://i.sstatic.net/vPdzU.jpg My attempt at constructing the request goes like this: let reqString = 'GET https://login.yandex.ru/info?format ...

What is the best way to add content to the nearest div with a specific class?

I'm attempting to use jQuery to identify and wrap images within text, then relocate them to another div. However, I am encountering difficulties getting it to function as intended. Below is the code that I have so far that appears to be effective: $ ...

"Utilizing Material-UI version 5 to efficiently collapse all subordinate nodes within the

My goal is to collapse a TreeItem and have all of its descendant TreeItems (including children and grandchildren) also collapse at the same time. Currently, when I collapse the parent TreeItem, the descendants disappear but when I expand it again they ar ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Storing information in a MySQL database with the assistance of AJAX and PHP

I recently encountered an issue while trying to insert a name and password into a MySQL table using a particular code snippet. Although the code triggered a success alert, the data was not successfully added to the table. Can anyone assist in resolving thi ...