What is the best way to bring in an array from a local file for utilization in a Vue 3 TypeScript project?

Encountering a TS7016 error 'Could not find a declaration file for module '../composables/httpResponses'. '/Users/username/project/src/composables/httpResponses.js' implicitly has an 'any' type.' while attempting to import an array from a local .js file into a view component. The file structure is as follows:

httpResponses.js

export const httpResponses = [
  {
    "code": 301,
    "message": "Moved Permanently",
  },
  {
    "code": 401,
    "message": "Unauthorized",
  }
]
interface.ts

export interface HttpResponse {
  code: number;
  message: string;
  description: string;
}
App.vue

<template>
  <h1>testing</h1>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { httpResponses } from './httpResponses';
import { HttpResponse } from './interface'

export default defineComponent({
  name: 'App',
  data() {
    return {
      matchingResponse: undefined as HttpResponse | undefined
    }
  },
  mounted() {
    this.matchingResponse = httpResponses.find(response =>
    response.code === 401)
  }
})
</script>

Seeking guidance on correcting this issue. How should this task be approached? Extensive research yielded information that such errors are common with third-party packages, but in this case, it's related to an internal file.

The original project can be accessed here. An attempt was made to create a minimal reproducible code sandbox here, however, unsuccessful due to the absence of Vue3/TS boilerplate support.

Answer №1

To change the name of `httpResponses.js` to `httpResponses.ts`, and define the array that it returns using the interface `HttpResponse`, follow these steps:

import { HttpResponse } from './interface';

export const httpResponses: Array<HttpResponse> = [
 .....
]

Afterwards, in the file `App.vue` :

<script lang="ts">
import { defineComponent } from 'vue';
import { httpResponses } from './httpResponses';
import { HttpResponse } from './interface';

export default defineComponent({
  name: 'App',
  data() {
    return {
      matchingResponse: {} as HttpResponse | undefined
    }
  },
  mounted() {
    this.matchingResponse = httpResponses.find(response =>
    response.code === 401)
  }
})
</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

Conditional application of Angular animations is possible

After implementing the fadein effect from Angular-Animations in my ASP.NET based Angular project, I encountered an issue where only the first row is faded-in while the other rows are not displayed when using *ngIf. Here is a snippet of the code: <ng-te ...

Developing a dynamic input field module in Vue.js

I am currently working on a reusable component for input fields that allows me to define them easily within one component tag using props. My goal is to make the component versatile enough to be used as text, date, password, number, etc., based on a condit ...

Is There a Comparable Feature to *ngIf in DevExtreme?

Currently, I am diving into the world of webapp development using DevExtreme. As a novice in coding, this is my first time exploring the functionalities of DevExtreme. Essentially, I am seeking guidance on how to display certain elements based on specific ...

Customize the asset path location in Webpack

I am currently working on a Vue application that utilizes Webpack for code minimization. Is there a method to dissect the chunks and adjust the base path from which webpack retrieves the assets? For example, by default webpack fetches assets from "/js" o ...

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

Derivation of the general function parameter

To provide a solution to this problem, let's consider the example below where a function is used. The function returns the same type that it accepts as the first argument: function sample<U>(argument: (details: U) => U) { return null; } ...

A more efficient method for incorporating types into props within a functional component in a TypeScript-enabled NextJS project

When dealing with multiple props, I am looking for a way to add types. For example: export default function Posts({ source, frontMatter }) { ... } I have discovered one method which involves creating a wrapper type first and then defining the parameter ty ...

Why am I encountering issues accessing a child property in TypeScript?

Here is some TypeScript code that I am working with: export interface SelectQuery_thing { __typename: "ThingQueryPayload"; content: (SelectQuery_thing_content | null)[]; pageInfo: SelectQuery_thing_pageInfo; } export interface SelectQuery_thing_con ...

The TypeScript command tsc -p ./ is causing errors in the typings modules

Whenever I try to execute the typescript command tsc -p ./, I encounter an error. This issue seems to be occurring with es6-shim and some other node packages. Below is my package.json: "scripts": { "vscode:prepublish": "tsc -p ./", "compile": "t ...

Troubleshooting: Vue and TypeScript Components Not Communicating

Vue is still fairly new to me and I'm struggling with this issue. Despite following code examples, my implementation doesn't seem to be working correctly. The component I defined looks like this: <template> <div class="row"> ...

The Typescript object may be null even with its initial value set

1: let a: Record<string, any> | null = {}; 2: a['b'] = 2; Encountered the TS2531: Object is possibly 'null' error on Row 2 despite having an initial value. To address this issue, the code was updated as follows: 1: let a: Record ...

Transfer the text from one cell and insert it into the "neighbor" cell of a different column when the content is editable

present situation: Clicking on a row fills the entire row of another column, instead of just filling a single row. <p class="p-of-that" v-html="thatText" contenteditable @click="writeThat(myArr, $event)" ></p& ...

Is VSCode disregarding tsconfig.json and compiling individual files, causing misleading error messages to appear?

After updating typescript, angular, and all the libraries in my project, I encountered a new issue that was not present before. Although I successfully ensured that my code builds without any errors or warnings from the command line, Visual Studio Code sta ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...

Creating a Vue.js component with dynamic data

Recently, I started working with Vue.js and have been experimenting with it for a few days. One of the challenges I'm facing is trying to dynamically add a new div element with text input every time the enter button is pressed. I would greatly appreci ...

Using TypeScript to convert a JSON date string into a Date object

The backend is sending me a JSON data structure that resembles the following: [{ "schedulingId": "7d98a02b-e14f-43e4-a8c9-6763ba6a5e76", "schedulingDateTime": "2019-12-28T14:00:00", "registrationDateTime": "2019-12-24T16:47:34", "doctorVie ...

What is the best way to save code snippets in Strapi for easy integration with SSG NextJS?

While I realize this may not be the typical scenario, please listen to my situation: I am using Strapi and creating components and collections. One of these collections needs to include code snippets (specifically typescript) that I have stored in a GitH ...

What's the trick to inserting a "dot" beneath a DatePicker?

Could someone assist me in adding a small "dot" below certain dates on MUIX DatePicker, similar to the example shown here? Thank you. ...

A feature that retrieves specific attributes from a type based on user-defined criteria

I am dealing with a group of types/interfaces that share common properties, but some cases do not utilize all of these properties. I would like to develop a function where only the names of the properties are passed to it. Here are the shared properties: ...

Learn the process of typing a property that will be displayed as a dynamic HTML element component

Looking for a way to render an HTML element dynamically based on a prop in a React component? interface ButtonProps { children: ReactNode; className?: string; as?: string; <--- ? [key: string]: unknown; } const Button = forwardRef({ children, ...