vue3+ts: shims-vue.d.ts

1. Introduction to this article

uniapp (3.8.4.20230531) + vue3 + ts + vite item

When building this base project, a wavy red line appeared as shown in the figure. The code is running normally, but it looks uncomfortable. So I searched and found very little information. It may have something to do with the inaccuracy of my question. Some people say delete tsconfig .js is ok, I tested it, the result is really ok, but this is by no means what I want, this obviously ignores the meaning of the tsconfig.js file, continue to study!

Two, typescript type assertion

1. Use the as keyword to implement type assertion.
2. The type after the keyword as is a more specific type (videoTiem is a subtype of videoList).
3. Through type assertion, the type becomes more specific, so that the unique properties or methods of videoItem can be accessed.

Sometimes you will be more specific about the type of a value than TS. At this time, you can use type assertion to specify a more specific type.

Thinking of this sentence, I tested it, and it worked, but I was still not satisfied. This is not what I want

Three, shims-vue.d.ts

shims-vue.d.ts is a TypeScript type definition file that helps the compiler recognize Vue.js syntax and provide type checking when writing Vue.js applications using TypeScript. It provides type definitions for some global variables and functions in Vue.js, such as Vue constructors, Vue instance options, etc. In the absence of a shims-vue.d.ts file, the compiler may report errors or warnings because it does not recognize the syntax of Vue.js.

The root cause of the problem has been found, which is the configuration problem of this file. The modified file is recorded as follows

// import 'vue' // 必须要引入vue,否则就成了覆盖
import { StateType } from '@/store/index.d'
import { InjectionKey } from 'vue'
import { Store } from 'vuex'

/**
 * 这里为什么用vue,而不用@vue/runtime-core,是因为使用pnpm安装依赖,node_modules中没有@vue/runtime-core,
 * 会导致找不到模块而类型声明失败。
 */
// declare module '@vue/runtime-core' {
declare module 'vue' {
    interface ComponentCustomProperties {
        // 这里扩展this.$store,还可以在这里对this添加其他的声明
        $store: Store<StateType>
    }
}

// 扩展useStore声明
declare module 'vuex' {
    export function useStore<S = StateType>(injectKey?: InjectionKey<Store<S>> | string): Store<S>
}

// 扩展mock
declare module 'mockjs' {
    /** 所有已注册的mock规则  */
    const _mocked: Record<string, any>
}

export {}

4. Welcome to exchange and correct, follow me, and learn together.

5. Reference link

Small program-uniapp: basic configuration and use of uni-app-base project, available out of the box_snow@li's blog-CSDN blog

TypeScript: Proficiency in TypeScript_snow@li's Blog - CSDN Blog

Guess you like

Origin blog.csdn.net/snowball_li/article/details/131254596