No errors encountered during compilation for undefined interface object types

Hey there, I'm currently exploring the Vue composition API along with Typescript.

I'm facing an issue where I am not receiving any errors when an interface does not align with the specified types for that interface.

Although my IDE provides auto suggestions and everything seems to work fine, mismatches like passing a number to a string type go unnoticed during compilation.

Below is a simple example:

Vue file:

<template>
  <div class="flex flex-col">
    <h1 class="flex justify-center">Test View</h1>
    <TestComponent
      :dataset="{
        strCustomerName: 12345,
      }"
    />
  </div>
</template>
<script setup lang="ts">
import TestComponent from "@/components/TestComponent.vue";
</script>

The above Vue file imports a component and passes an object named dataset along with it.

Test component:

<template>
  <h1 class="text-9x1 flex">Hello {{ props.dataset.strCustomerName }}</h1>
</template>

<script setup lang="ts">
import { defineProps } from "vue";

type FormType = {
  strCustomerName: string;
};

interface FormProperties {
  dataset: {
    type: FormType;
    required: true;
  };
}

const props = defineProps<FormProperties>();

console.log("We are props: ", props.dataset);
</script>

In this test component, I specify to Vue that I expect a dataset object to be passed as a property in FormProperties. I also define the structure of the object using FormType. However, the problem arises when a number is passed instead of a string without any error being thrown. Even if a key that is not defined in FormType is passed, no error is generated.

So why am I not getting errors for incorrect types or undefined keys? Is this the expected behavior or is there a way to rectify this?

Answer №1

Utilizing the `defineProps` Method

The declaration format for the `defineProps` function specifies the type of each prop, so in this scenario, calling `defineProps<FormProperties>()` instructs Vue to define a prop named `dataset` that consists of two fields:

  • type, which is of type FormType, containing a property called strCustomerName with a data type of string.

  • required, which must be set to true (any other value would trigger an error).

It seems like you intended to utilize the runtime declaration method with `defineProps`, but it should be provided as a function argument within the `defineProps` call:

import type { PropType } from 'vue'

defineProps({
  dataset: {
    type: Object as PropType<FormType>,
    required: true,
  }
})

Alternatively, if opting for the type declaration approach, update the `FormProperties` interface to solely include the data fields:

type FormType = {
  strCustomerName: string;
};

interface FormProperties {
  dataset: FormType;
}

defineProps<FormProperties>();

Remember, you cannot mix both methods. The `defineProps` function accepts either the type declaration or the function argument, not both simultaneously.

Identifying the Error

If you were using Volar (the official VS Code extension for Vue), a notification about the error in your initial code would have been displayed:

https://i.stack.imgur.com/tCFcJ.png

Similarly, if you utilized vue-tsc for type checking, the error would have been outputted in the console:

$ vue-tsc --noEmit
src/components/MyComponent.vue:2:52 - error TS2339: Property 'strCustomerName' does not exist on type '{ type: FormType; required: true; }'.

2   <h1 class="text-9x1 flex">Hello {{ props.dataset.strCustomerName }}</h1>
                                                     ~~~~~~~~~~~~~~~


Found 1 error in src/components/MyComponent.vue:2

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

Ways to solve VScode gutter indicator glitches after switching text editors?

When my active function is running, I have a specific updateTrigger that ensures certain actions are taken when the activeTextEditor in vscode changes: const updateTrigger = () => { if (vscode.window.activeTextEditor) { updateDecorations(con ...

mat-table dataSource is not functioning properly with REST API integration

I'm facing an issue while trying to populate a Material Table with data. My model Block has fields such as id, date, etc. The API call is made in data.service and the function getAllBlock() fetches the blocks. I tested this in the app.component.html ...

What is the best way to trigger a Redux Toolkit action within a React Router DOM action?

My router setup looks like this: const router = createBrowserRouter([ { path: "/", element: <MainLayout />, errorElement: <Error />, children: [ { path: "/inventory", element: <Inve ...

Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn ...

Learn how to update a Vue.js method dynamically by using the route parameters

After creating a reusable component for image uploads stored in Firebase storage, I encountered an issue when trying to reference the images in the database with section-specific labels. The problem arises when I attempt to name the location for the "down ...

Exploring the history and present state of Vue lifecycle hooks

Is there a way to access previous and current data in the updated lifecycle hook in Vue, similar to React? I want to be able to scroll a list of elements to the very bottom, but for this I need: The already rendered updated DOM (to calculate the scroll) ...

When attempting to utilize TypeScript with Storybook, Jest may encounter an error stating, "Incompatible types for property 'id'."

Currently, I'm exploring the use of stories in my unit tests with Jest + RTL to reduce redundancy. However, I've encountered an error stating "Types of property 'id' are incompatible" when passing arguments that are also used in my stor ...

What is the recommended way to compile SCSS module in a Vue component using Laravel Mix?

I recently attempted to set up the webpack configuration in my Laravel project. However, I encountered an issue where modular CSS was working perfectly fine without the lang="scss" attribute, but now I need to work with SCSS. I'm struggling to figure ...

tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array? I previously attempted to find the maximum values for just three keys. getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) { var val1 = Math.max.apply(Math, v ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

Is it possible to utilize an enum for typing an array variable?

Is there a way to use an enum to define the valid types that an array can contain? I have been unable to find a solution so far, and I am curious if it is feasible. Below is the example code I have tried: interface User { name: string; } interface Ad ...

Testing Angular 11 methods using Jest unit tests within a .then block

Currently, I am running jest unit tests in Angular 11 and facing an issue while testing methods within the .then method. It seems like the test methods are not being executed at the expect method. I need guidance on how to structure the test code to ens ...

Creating a high-quality select input component in Vue 3 that functions effectively

Struggling to implement pagination using a select field, I am unsure how to properly use the v-model and value properties. Below is my current implementation: This is the select/pagination section in the component: <p v-on:click="back" ...

Utilizing Express JS: Invoking a function within my class during routing operations

Currently, I am in the process of developing a MERN Application using Typescript. I seem to be encountering an issue with this within my class. When utilizing this code snippet: router.post("/create", user.createNewUser); It becomes impossible ...

Tips on how to retrieve a stubbed Observable<void> in RxJS

Currently, I am attempting to stub an API and would like to retrieve a stubbed response from my Service. The method in my service appears as follows: public addItem(item): Observable<void> { this.listOfItems.push(item); return of(); } As f ...

Utilizing Bootstrap Vue to retrieve a specific object from an array of objects using the b-form-select component

While I was able to find a solution to my issue, I can't help but feel slightly unsatisfied with the complexity of the current method. Is there a simpler way to achieve this? Ideally, I would like to have similar HTML code where all I need to do is ma ...

Prevent Object Prop Modification in Vue.js

Within the parent component, I initially have an empty filter object like this: {}. The child component, called filter component, is a child of the parent component and here's how it is implemented: <filter-component :filters.sync="filters&q ...

In Typescript, is it correct to say that { [key: string]: any } is identical to { [key: number]: any }?

Recently diving into Typescript has been an interesting journey, especially when stumbling upon weird language behaviors. After writing the following code snippet, I was surprised to see that it compiled and executed successfully: let x: { [key: string]: a ...