TypeScript throws an error if trying to access an Object variable using a String

While the code below is functioning as intended, I am encountering an error in the VS Code Typescript compiler stating that "Type 'String' cannot be used as an index type". Oddly enough, using a string literal instead of a variable like sentence['a-string'] allows the Typescript to run without issue.

I am content with how the code is currently set up, but I would like to know if there is a way to resolve this error. Alternatively, is there another method I can use to access sentence[display]?

const props = defineProps<{
    sentence: Sentence,
    display: String,
}>()
<div v-html="sentence[display]" />

The code is functional, however, the Typescript error persists.

Answer №1

If you want to address this issue, you have the option of adding the following code snippet:

 [key: string]: string;

Alternatively, you could create an interface called Sentence and include the key value inside it like so:

interface Sentence {
  [key: string]: string; // This allows indexing with a string key to retrieve a string value.
}

Additionally, as mentioned by @Estus Flask, it's important to note that "string" and "String" are not interchangeable.

  const props = defineProps<{
    sentence: Sentence,
    display: string,
}>()

Answer №2

If you want to inform TypeScript that the object can be accessed by strings, you can do so with the following code snippet:

const properties = defineProps<{
    [key:string]: any, /* or specify your expected type */
    phrase: Sentence,
    view: String,
}>()

Answer №3

To designate display as a key within the Sentence object, you can do the following:

const props = defineProps<{
    sentence: Sentence,
    display: keyof Sentence,
}>()

This approach will generate error messages if an incorrect value is passed to display, and it will enable your IDE to provide suggested values.


In scenarios where the keys of Sentence are not fixed (e.g.,

type Sentence = {[key: string]: any}
), but the keys of a specific object can be deduced, you can utilize generics to specify those concrete keys:

<script setup lang="ts" generic="O extends Sentence">

const props = defineProps<{
    sentence: O
    display: keyof O
}>()

By implementing this method, you will receive errors if the value for display does not align with one of the actual keys in the object.

It's worth noting that Vue currently struggles to infer the correct type in templates, which means that using {{ sentence[display] }} in the template may lead to an error. Nonetheless, you can create a computed property as a workaround.

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

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

The connection to fonts.googleapis.com for the stylesheet sometimes experiences issues with loading properly or becoming corrupted

My project was initiated using the Vue CLI + Vuetify new project templates. The standard font loading statement in index.html is as follows: <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> Most ...

Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on Gi ...

Exploring the firestore section with vuefire for seamless access to methods

I am attempting to access a method in the firestore section of vuefire, but encountering the following error: vue-router.esm.js?8c4f:2257 TypeError: Cannot read property 'messagesWith' of undefined at eval (Chat.vue?62f3:214) This is the lin ...

"Excessive label length on yAxis causing display issues in chart with chartJs

I'm facing an issue with excessively long labels on the Y-axis while using the "chartjs" and "vuejs" modules. To provide a visual representation of the problem, I have attached an image: View Image Here Below is the snippet of my code where the prob ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

Typescript in Firebase Functions organization

Struggling with typescript organization in my firebase functions. I'm fine keeping trigger functions in index.ts for now, but need help organizing other utility functions elsewhere. Current index.ts setup: import * as functions from 'firebase-f ...

Consolidate multiple sorting functions into a single function to effectively sort by column

Can someone help me simplify my sorting function for array columns? Currently, I have multiple functions like the one below for each column: sort() { if (this.sortAsc == false) { this.tab.sort((a, b) => { return a.name.localeCompare( ...

What could be causing my data to undergo alterations when transitioning from a frontend form submission to a backend API?

In my experience with Next.js 13 and Prisma, I encountered a peculiar issue. I had set up a basic form to collect user information for an api request. Oddly enough, when I printed the data right before sending it, everything seemed fine. However, upon arri ...

What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values. I am currently struggling to iterate through these ...

How can I make Cesium, SystemJS, and Angular2 compatible with each other?

Could anyone provide a working example of using SystemJS (not Webpack) with Angular2 (in TypeScript, not Dart) and Cesium (npm)? I came across a blog post on cesiumjs' site that discusses this: The author mentioned, "You can't simply do a requi ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Effective strategies for extracting value from asynchronous Angular events that return Promises

When it comes to subscription blocks, extracting the value from my API is possible. var data = null; this._timinServiceProxy.getDateFromNTP().subscribe(result => { data = result; console.log(data); // The expected result }); console.log(data); ...

Implementing TypeScript in React FlatList

While TypeScript is a powerful tool, sometimes it feels like I'm working more for TypeScript than it's working for me at the moment. I'm currently using a FlatList to display restaurant results in a Carousel. const renderRestaurantRows = ( ...

Changing background color during drag and drop in Angular 2: A step-by-step guide

A drag and drop container has been created using Angular 2 typescript. The goal is to alter the background color of the drag & drop container while dragging a file into it. Typescript: @HostListener('dragover', ['$event']) public onDr ...

Sending the value of "username" between two components within Angular 2

I have a good understanding of nesting child components within parent components in Angular 2, but I'm a bit unclear on how to pass a single value from one component to another. In my scenario, I need to pass a username from a login component to a cha ...

Is there a way to update JSON data through a post request without it getting added to the existing data?

Hello, I am currently delving into Angular2 and encountering a problem concerning RestAPI. When I send a post request to the server with a JSON file, I intend to update the existing data in the JSON file; however, what actually happens is that the new data ...

Issue accessing page from side menu in Ionic 2 application

I am experiencing an issue where the page does not open when I click on it in the side menu. Here is my app.component.ts file: this.pages = [ { title: 'NFC Page', component: NfcPage, note: 'NFC Page' }, ...

I am facing an issue where the data is not displaying as expected in the console

Having trouble with my Vue app where I have two methods - one to retrieve data from my Laravel backend and the other to use that data. The issue is that the second method is not able to grab the data. Below is a sample of my code: <template> ...

Is there a way to turn off linting while utilizing vue-cli serve?

I am currently running my project using vue-cli by executing the following command: vue-cli-service serve --open Is there a way to stop all linting? It seems like it's re-linting every time I save, and it significantly slows down the process of ma ...