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

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

Trouble encountered while using useRef in TypeScript

I'm encountering an issue with the code below; App.tsx export default function App() { const [canvasRef, canvasWidth, canvasHeight] = useCanvas(); return ( <div> <canvas ref={canvasRef} /> </div> ) ...

Unintentional GET request triggered by Axios baseURL

I have encountered a strange issue where defining axios.defaults.baseURL = baseUrl; results in an unexpected GET request right after initializing my Vue app. Any assistance would be greatly appreciated! Below are images showing the code and network reques ...

Unexpected 'TypeError: Unable to access property 'removeChild' of null" error causing confusion

When I interact with my application, a specific button changes its text when clicked. However, upon clicking it again, the text reverts back to its original caption. Unfortunately, I encountered an error message while doing this: An unexpected issue oc ...

Utilizing a method from a separate class in Ionic 2

Having trouble using the takePicture() function from camera.ts in my home.ts. I keep getting an error message saying "No provider for CameraPage!" Any assistance on how to resolve this issue would be greatly appreciated, as I am new to this language and ju ...

Converting a string to a number in an Angular template

Within my select box, I am capturing the selected value and binding it to the variable startingYear. However, I need the type of startingYear to be a number, but it is currently registering as a string. Is there a way to convert it to a number? console ...

Determining function return property type in Typescript by mapping interface argument property

In order to manage messaging between the browser and a web worker, I have developed a generic class. Each side creates a class that can send specific messages and acknowledge them on the other side with a returned result in a payload. The implementation is ...

Custom markers on Google Maps are fixed in place and cannot be dragged

I'm having an issue with making a Google Map custom marker draggable in a Vue component. Even though I have set draggable = "true", the marker does not move when dragged. Can anyone help me figure out how to make the marker draggable and retrieve the ...

Issues encountered when trying to deploy Nuxt.js on GitHub Pages

Recently, I delved into learning Nuxt.Js and encountered an issue when trying to deploy on GitHub Pages. I followed the instructions diligently: https://medium.com/@kozyreva.hanna/nuxt-js-gh-pages-deployment-73b88aa3aa65 An endless nuxt-loading loop dis ...

Managing a click event with an element in React using TypeScript

Hey there, I'm pretty new to TypeScript and React. I have this event where I need to identify the element that triggered it so I can move another element close to it on the page. However, I'm facing some challenges trying to make it work in React ...

Ionic has been experiencing issues with inaccurate boolean results being generated by Angular typescript

I have created a random number generator that requires the user to input a maximum and minimum value to generate a random number within that range. The application will show an error under two conditions: If either of the numbers entered is negative If t ...

Transferring information between Puppeteer and a Vue JS Component

When my app's data flow starts with a backend API request that triggers a Vue component using puppeteer, is there a way to transfer that data from Backend (express) to the vue component without requiring the Vue component to make an additional backend ...

Beginning the deployment of a Nuxt SSR application on Azure with the build files

According to the Nuxt documentation, running yarn build will result in Nuxt.js creating a .nuxt directory containing everything ready for deployment on your server hosting. After reviewing a couple of other guides, it appears that additional items require ...

What can cause the reactive value to fail to update in a Vue template?

In my application, I encountered a strange issue where a h3 tag containing a title bound to a reactive data property from a Firestore database would sometimes not display properly after a page reload. Oddly enough, when accessing the page through client-si ...

A guide on how to assign a placeholder as the default value for a date picker

Currently using Vue3 with options API, and this question does not pertain to date formatting. Looking at the code provided on StackBlitz here, the default format for the date being initially set is dd.mm.yyyy. I am interested in knowing how to set the date ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

Guide on integrating Amazon S3 within a NodeJS application

Currently, I am attempting to utilize Amazon S3 for uploading and downloading images and videos within my locally running NodeJS application. However, the abundance of code snippets and various credential management methods available online has left me fee ...

Using a loop variable within a callback function in JavaScript/TypeScript: Tips and tricks

I have a method in my TypeScript file that looks like this: getInitialBatches() { var i = 0; for (var dto of this.transferDTO.stockMovesDTOs) { i++; this.queryResourceService .getBatchIdUsingGET(this.batchParams) ...

Encountering a Laravel error: Unexpected token when implementing Vuex

Recently, while working with Laravel and Vue.js, I encountered an unexpected token error when trying to access a method from my store using Vuex mapAction. The issue lies within the three dots (...) before the mapActions in the following code snippet foun ...