Unlocking the Power of Typescript in Your Laravel Mix and Vue SFC Workflow

Can Typescript be used in Vue single file components (SFC) with Laravel Mix?

If so, how can this setup be implemented?

The current setup includes Laravel Mix 5.0, Typescript 3.7.5, and Vue 2.5.17.

A sample single file component written in Typescript is SingleFileComponent.vue:

<template>
  <div>
    <ul
        v-for="item in items"
        v-bind:key="item.id">
        <li>{{ item.message }}</li>
    </ul>
  </div>
</template>
<script lang="ts">
import Axios from 'axios';

export default {
  data() {
    return {
      items: [],
    }
  },
  mounted() {
    Axios.get('/api/get-stuff').then(res => {
      this.items = res.data;
    })
  },
}
</script>

This configuration has been set up in webpack.mix.js:

const mix = require('laravel-mix');

mix.ts('resources/js/app.ts', 'public/js')
   .webpackConfig({
      resolve: {
         extensions: ["*", ".js", ".jsx", ".vue", ".ts", ".tsx"]
       }
   });

When running npm run watch, the following error occurs:

ERROR in /path-to-file/SingleFileComponent.vue.ts
[tsl] ERROR in /path-to-file/SingleFileComponent.vue.ts(21,12)
  TS2339: Property 'items' does not exist on type '{ data(): { items: never[]; }; mounted(): void; }'.

Answer №1

For optimal use of SFC with Typescript, it is recommended to extend:

<script lang="ts">
import Axios from 'axios';
import Vue from 'vue';

export default Vue.extend({
  ...
})
</script>

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

What causes the difference in behavior between packed and non-packed generics?

When attempting to exclude properties outside of generics, it functions properly but results in a breakdown within the generic context. The issue lies in the fact that Omit<Thing, 'key1' | 'key2'> transforms into Omit<Thing, &a ...

What steps can I take to avoid cross-project contamination within an Angular workspace?

Imagine having a project structured like this: projects |-app1 |-app2 |-common node_modules pakcage.json tsconfig.json angular.json ... (other root files) Currently, in a file within app1, you can have an import statement like this: import { Repository } ...

Storing a portion of JSON data within a function called in the HTML document

I've been working with Angular and need to save a portion of JSON data in a variable within a function that is called in an HTML file: <select id="postazione" onchange="postazioneSelezionata()"> <option value="" selected disabled >Cho ...

Creating a Nuxt 2 page that utilizes dynamic parameters

My link is constantly changing with the path /user/reset/{params1}/{params2}/{hash}/json. I have set up a page at /pages/user/reset/_slug.vue, but it only works with one parameter. What steps should I take to create a page that supports this entire path? ...

How can TypeScript be effectively utilized with global packages?

Utilizing the global package to incorporate certain enzyme methods in test files without the need for importing: import { configure, shallow, render, mount } from 'enzyme'; ..... global.shallow = shallow; global.render = render; global.mount = ...

The JSX component is successfully rendered on the Nuxt dev server, but encounters issues on the production version

I'm facing an issue with my Nuxt app component that utilizes JSX. Everything works fine locally when I use `npm run dev`, but the rendered output is incorrect after executing `npm run build`. Below is the code for the component: <script> import ...

Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks! Update: I want to simplify my code and avoid using app.get(...) Here's my code snippet ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

Creating a TypeScript array of objects that aligns with a specific interface: A step-by-step guide

In the code snippet below, there is a Typescript interface called Product. The goal is to ensure that every object in the products array follows this interface. However, the implementation process has been challenging so far. Various attempts like products ...

Facing Syntax Errors When Running Ng Serve with Ngrx

Currently, I am enrolled in an Angular course to gain proficiency in ngrx. In a couple of months, I will be responsible for teaching it, so I am refreshing my memory on the concept. Strangely, even after installing it and ensuring my code is error-free, er ...

Object-oriented programming (OOP) principle - deciding on the placement of the method "getUserMembershipStorageSize()"

Currently studying Object-Oriented Programming (OOP) concepts and facing a challenge. I have two classes: User Class (user model) and Photos class. I need to create a method that calculates the currentPhotoStorageSize available for the user, considering th ...

"Troubleshooting: Vue ChartJS Line Chart fails to show data

Hey there! I'm currently working on integrating Chart.js with the vue-chartjs wrapper to build a Line Chart using data retrieved from my API. The data is being successfully logged to the console without any errors, but for some reason, the Line Chart ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Updated TypeScript definitions for Node.js version 2.0 available now with @

I've recently started using the new @typings feature, and I noticed that when I run npm install --save @types/react, it creates an @typings folder within the node_modules directory. Additionally, it adds the dependency @types/react: ^0.14.43 in the pa ...

The term "define" is not recognized when constructing a Next.js application

Currently, I am working with Next version 10.0.1 and React 17.0.2. While attempting to build my Next app, I encountered the following error: ReferenceError: define is not defined at Object.<anonymous> (/Users/username/Desktop/project/node_module ...

Vue: Utilizing computed properties to monitor changes in offsetHeight of elements

I am working on a component that requires an array of 50 objects to be passed as a prop. <template> <div v-for="(item,index) in items" ref="items" :key="index"gt; // </div> </template> props: ...

Using an array with Vuex v-model

Is there a way to use v-model with vuex for an array property? In the past, I was able to bind properties without Vuex but now that I am using Store, how can I convert it to work with newAds within the store? <div v-for="ad in newAds" :key="ad.id"> ...

Tips for passing a query parameter in a POST request using React.js

I am new to working with ReactJS and I have a question about passing boolean values in the URL as query parameters. Specifically, how can I include a boolean value like in a POST API call? The endpoint for the post call is API_SAMPLE: "/sample", Here is ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

Enhancements to managing universal configuration object across the entire application

My current project involves working on an application with multiple products. To streamline product-specific configuration and eliminate the need for excessive if-else statements, I am looking to implement product-specific config keys that are consistently ...