Issue TS2322: Incompatible types - Attempting to assign a 'Function' type to a 'string' type

I am working on creating a question and answer catalog that allows me to select questions along with their respective answer options from a String Array. However, I encounter an error when trying to assign this.currentQuestion with the question from the catalog, as well as with the answers.

TS2740: Type 'Function' is missing properties like pop, push, concat, join, and more from type 'string[]'.

Below is the code snippet:

data() {
    return {
      question0: "What is 1+1?",
      answers0: ["2", "3", "1", "4"],
      questionCatalogue: [this.question0],
      answerCatalogue: [this.answers0],
      currentQuestion: "",
      currentAnswers: ["", "", "", ""]
    };
  },
  methods: {
    initNewQuestion: function() {
      this.currentQuestion = this.questionCatalogue[0];
      this.currentAnswers = this.answerCatalogue[0];
    }
  },

I expected that calling for this.questionCatalogue[0] would provide me with this.question0 which is a String, allowing me to assign it to this.currentQuestion. Why does it not work as expected?

Answer №1

The function obj.questionCatalogue returns an array, while the variable this.currentQuestion is of type string. Check out the image linked below for more details. click here to view the image

Answer №2

From my perspective, it would be beneficial to organize all your questions directly within the question catalog as separate objects.

One approach could be structuring it like this :

{
   question: "What is the capital of France?",
   answers: ["London", "Paris", "Berlin", "Rome"],
   correctAnswerIndex: 1
}

You can then store all your questions in a questions array.

Furthermore, you can modify your initNewQuestion method to look like this :

methods: {
    initNewQuestion: function() {
      const questionItem = this.questionCatalogue[0]
      this.currentQuestion = questionItem.question;
      this.currentAnswers = questionItem.answers;
    }
},

Illustrative example using vue2 without TypeScript

new Vue({
  el: '#app',
  data: () => ({
     currentQuestion: "",
     currentAnswers: [],
     questionsCatalog: [
        {question: "What is the capital of Spain?", answers: ["Madrid","Barcelona","Seville","Valencia"]}
     ],
  }),
  
  mounted(){
     const question = this.questionsCatalog[0]
     this.currentQuestion = question.question
     this.currentAnswers = question.answers
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h1>{{currentQuestion}}</h1>
  <ul>
    <li v-for="(answer, index) of currentAnswers" :key="index">{{answer}}</li>
  </ul>
</div>

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

Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows: <template> <div id="app"> <div id='container'> ...

Discover the secret to creating an efficient TypeScript function that offers autocomplete with enum values

I'm attempting to achieve a scenario similar to the code below: enum Color { RED="RED", GREEN="GREEN", BLUE="BLUE" } function setColor(color:Color) { } However, when I attempt to call the function like this: setColor("RED"), I encounter the ...

Unable to utilize the data-placed value in the template; only the props value is functional

I am utilizing the value from props and changing the class based on it. Below is the code that is currently working: <div class="modal" :class="{'is-active': aa}" > However, when I attempt to make a check based on the value of isActive fr ...

What is the best way to determine the data type of one property in an array of objects based on another property

I have been working on creating a straightforward parser that relies on rules provided by the constructor. Everything seems to be running smoothly, but there are some issues with data types. interface RuleBase { parse(text: string, params: Record<stri ...

Dealing with a multi-part Response body in Angular

When working with Angular, I encountered an issue where the application was not handling multipart response bodies correctly. It seems that the HttpClient in Angular is unable to parse multipart response bodies accurately, as discussed in this GitHub issue ...

"Sorry, but window.print function is not available in this environment

Whenever I try to execute something in jest, I keep encountering the same error message: console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Not implemented: window.alert at module.expor ...

Versatile typing capabilities

Is it possible to have a function that takes a configuration object as its parameter, specifying which properties in a data object should be read? The configuration object has two properties that correspond to keys in the data object. The configuration ob ...

Is it possible to globally modify the component reference <dropdown-component> name in Angular during runtime in a dynamic manner?

I am currently working on an application that utilizes a component called "dropdown-component" throughout its pages. However, due to specific business requirements, I have been tasked with replacing "dropdown-component" with "custom-dropdown-component". Un ...

The input of type 'string' cannot be assigned to type 'ChartType'

html code snippet <div style="width: 100%; display: block"> <canvas *ngIf="loaded" baseChart [data]="barChartData" [labels]="barChartLabels" [options]="bar ...

Utilizing Bootstrap-Slider in Vue with TypeScript

Attempting to incorporate a bootstrap-slider onto my webpage using a TypeScript-based Vue backend within an ASP.NET Core framework. Utilizing the standard Vue.js template with TypeScript in ASP.NET Core. Have added the bootstrap-slider types via npm inst ...

Should Vue be imported directly from `'vue'` within a single component?

I recently came across this documentation: import Vue from 'vue' import Chartkick from 'vue-chartkick' import Chart from 'chart.js Vue.use(Chartkick.use(Chart))' I am wondering if it's best to add this code to a single ...

In an oclif-cli interface similar to a mysql-client-cli, what is the process for presenting data retrieved from a database

Currently, I am in the process of building a CLI tool utilizing OCLIF Framework and TypeScript. One of the commands I have developed retrieves all values from the database successfully. However, once retrieved, I would like to display this data in tables f ...

Is it possible to get intellisense for Javascript in Visual Studio Code even without using typings?

Is it possible to have intellisense support in Visual Studio Code for a 3rd party library installed via npm, even if there is no typings file available? I have noticed this feature working in IntelliJ/Webstorm, so I believe it might be feasible. However, ...

The type 'unknown' cannot be assigned to type 'KeyboardEvent'. Error in file 'ts' (2345)

Currently delving into TypeScript and Angular, I encountered an issue in my textbook with an example that refuses to compile. I am unsure of how to resolve this problem. Below is the malfunctioning function: ngOnInit(): void { const logger = fromEvent ...

Configuring the default value for a selection menu in Vue3

Obtaining all available categories: const fetchCategories = async () => { let response = await axios.get(`/api/get_all_category/`) categories.value = response.data.categories } The structure of categories.value is shown here: https://i.sstatic.net ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

There were issues with React's compilation when integrating with antd UI

Whenever I try to compile, errors keep showing up even though I have imported from antd. I can't figure out what the problem is. These are the errors I encounter while compiling: Compiled with problems: ERROR in ./src/components/excelPage.js 130:85- ...

Http service not found

I am facing a problem with injecting HTTP into my Angular 2 application. Everything was working smoothly a few days ago, but now I am encountering this error: ORIGINAL EXCEPTION: No provider for Http! Here is the code snippet from main.ts: import { pl ...

Change a numeric value into a string within a collection of objects

Consider the following input array: const initialArray = [ { id: 1, name: 1 }, { id: 2, name: 2 }, { id: 3, name: 3 }, { id: 4, name: 4 } ]; The objective is to modify it ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...