environment
vscode
typescript4
vue3
Problem description
First of all, the configuration of global variables and methods in vue3 is different from that in vue2. If you are not clear, you can check the official instructions, but you encounter problems when using them in combination with typescript
:
axios.ts
// axios.ts
import axios from 'axios'
const app = Vue.createApp({})
// Global Custom Properties
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$axios: AxiosInstance;
}
}
app.config.globalProperties.$axios = axios
Any Vue
file
<script lang="ts" setup>
import { getCurrentInstance } from 'vue';
// First, here the proxy ts will report
// Property "proxy" does not exist on type "ComponentInternalInstance | null". ts(2339)
const { proxy } = getCurrentInstance()
// Then this error will be reported below
// Unsafe member access .$axios on an `any` value. eslint@typescript-eslint/no-unsafe-member-access
// Unsafe call of an `any` typed value. eslint@typescript-eslint/no-unsafe-call
proxy.$axios('')
The above is the whole content of error reporting. Next, let’s solve this problem
Problem-solving:
The first error is easy to understand. Because the return type of getcurrentinstance()
has null
, you can add assertions here
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// Add Assertion
const { proxy } = getCurrentInstance() as ComponentInternalInstance
2. However, after the correction, we found that there are still errors reported below
// Object may be "null".ts(2531)
proxy.$axios('')
This problem is easier to solve. Add after proxy
to filter the results of null
proxy?.$axios('')
Above, the problem is solved!
Similar Posts:
- [Solved] Vue3+ts+eslint Error: warning Unexpected any. Specify a different type, warning Delete `·` , Missing return type on function, Require statement not part of import statement
- [Solved] Vue3.X version error: Parsing error: Parsing error: Unexpected token
- TypeScript error TS1005: ‘;’ expected [How to Solve]
- Ionic Error: Failed to load resource [How to Solve]
- [Solved] ESLint Error: Failed to load config “standard” to extend from
- No undef check error in eslint
- Typescript IMPORT Global node_ Modules error
- Error-Do not use “//@ts-ignore“ because it alters compilation errors [How to Solve]
- [Solved] ESLint: ‘React’ was used before it was defined.(no-use-before-define)
- [vue/no-parsing-error] Parsing error: invalid-first-character-of-tag-name.eslint-plugin-vue Parsing error: invalid-first-character-of-tag-name.eslint(vue/no-parsing-error)