Reference to a variable in Typescript object

I have set up a static object:

const instruments = {
    "guitar": {
        tunings: ["E","A","D","G","B","E"]
    },
    "ukulele": {
        tunings: ["G","C","E","A"]
    },
    "baritone": {
        tunings: ["D","G","B","E"]
    },
    "mandolin": {
        tunings: ["G","G","D","D","A","A","E","E"]
    },
   "bass": {
        tunings: ["E","A","D","G"]
    }
}

and I am trying to invoke a function using the instrument's name to fetch the appropriate 'tunings' array:

    constructor(canvas : HTMLCanvasElement, tuningName : string, startFret = 0, noFrets : number) : any {
        const tuningsArr = instruments[tuningName].tunings;
        ...
}

However, TypeScript in VSCode is showing an error. How can I correctly access the desired tunings array based on the provided string?

Answer №1

Two different approaches can be taken to achieve this task.

One method involves utilizing the inferred type for the instruments constant, where you must specify to TypeScript that the instruments object's state remains constant by using as const:

const instruments = {
    "guitar": {
        tunings: ["E","A","D","G","B","E"]
    },
    "ukulele": {
        tunings: ["G","C","E","A"]
    },
    "baritone": {
        tunings: ["D","G","B","E"]
    },
    "mandolin": {
        tunings: ["G","G","D","D","A","A","E","E"]
    },
   "bass": {
        tunings: ["E","A","D","G"]
    }
} as const;
// ^^^^^^^

Another approach is to explicitly declare types and assign the appropriate type to the instruments variable:

interface Tuning {
    tunings: string[];   
}
interface Instruments {
    guitar: Tuning;
    ukulele: Tuning;
    baritone: Tuning;
    mandolin: Tuning;
    bass: Tuning;
}
const instruments: Instruments = {
    "guitar": {
        tunings: ["E","A","D","G","B","E"]
    },
    "ukulele": {
        tunings: ["G","C","E","A"]
    },
    "baritone": {
        tunings: ["D","G","B","E"]
    },
    "mandolin": {
        tunings: ["G","G","D","D","A","A","E","E"]
    },
   "bass": {
        tunings: ["E","A","D","G"]
    }
};

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

Typescript is facing an issue locating the declaration file

I'm encountering an issue with TypeScript not recognizing my declaration file, even though it exists. Can anyone provide insight into why this might be happening? Here is the structure of my project: scr - main.ts - dec.d.ts str-utils - index. ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

Declaring scoped runtime interfaces with Typescript

I need to create a global interface that can be accessed at runtime under a specific name. /** Here is my code that will be injected */ // import Vue from "vue"; <- having two vue instances may cause issues // ts-ignore <- Vue is only ava ...

Unusual occurrence in Angular 2: The root element's style properties are coming back as empty strings

Currently, I am exploring Angular2 and have reached a point where I want to implement dynamic style extension in Angular2 components. To clarify things further, here is some code: Main.ts import {bootstrap} from 'angular2/platform/browser'; ...

Ensuring Proper Image Size Validation in Angular 5

Currently, I am in the process of developing an Angular web application, and one of the functionalities involves photo uploads. I am looking to add validation for image size to detect if the uploaded image is too small and prompt errors accordingly. Belo ...

Tips for getting Nativescript listview to function properly

I am currently developing an app using nativescript and angular 2. I am facing some issues while trying to implement the nativescript listview component. Whenever I run the app, all I see is " [object object] ". Below is my view code : <grid-layout c ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

Pausing in a NodeJS HTTP request listener until receiving another response before proceeding

Essentially, this is a web proxy. Within a request listener, I am creating another http request, reading its response, and passing it to the main response. But I have the challenge of needing to wait for the secondary request to complete before continuing. ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

Issue encountered: Nuxt 3 fails to locate the useRoute import

Recently, I updated to the latest version of Nuxt and encountered an issue with the useRoute method. Even though it works, I keep getting a "Cannot Find name useRoute" error message. Can anyone help me figure out what might be missing? <script lang=&quo ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...

Drawing coordinate lines on a two-dimensional array that simulates a grid

Are you solving a challenging code problem from the advent of code series? Check out the problem description here. The task involves processing input data in the form of coordinate lines on a grid (x1,y1 -> x2,y2). The goal is to populate a 2D array wi ...

"I am having trouble calling the useStyles function in React with Typescript and Material-

There seems to be a problem with calling the useStyles function as it is throwing the following error message: This expression is not callable. Type 'never' has no call signatures.ts(2349) const useStyles: never Below is the complete code snip ...

Create a definition file containing a class that can be easily extended

I am attempting to define an interface in a declaration file: declare namespace Foo{ export interface Bar{ new(attrs, options) } } Then I want to inherit from this interface in my code: class Chunk extends Foo.Bar {} However, I encounte ...

Troubleshooting TypeScript: Issues with Object.assign and inheritance

After successfully using the code within an Angular project, I decided to switch to React only to find that the code is now producing unexpected results. class A { constructor(...parts: Partial<A>[]) { Object.assign(this, ...parts); } } cla ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...