Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include .d.ts file manually(locally)? Or How to use a user defined .d.ts file?

I'm studying nuxt.js and due to some reason I want to extend Vue's instance like this:

import Vue from 'vue'

Vue.prototype.$myProp = 'test'

const app = new Vue()

console.log(app.$myProp)

Following the guide at https://v2.vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins, I have create a file at types/test.d.ts with the content bellow:

declare module 'vue/types/vue' {
  interface Vue {
    $myProp: string;
  }
}

However, I don't know how to make it works.

I was receiving errors in my VSCode. Also receive errors when I executing tsc(Version 3.7.2):

index.ts:14:17 - error TS2339: Property '$test' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.

14 console.log(app.$test)

I have tried to using a tsconfig.json in the root directory, but not work:

{
    "compilerOptions": {
        "typeRoots": [
            "types/test.d.ts"
        ]
    }
}

I have also tried insert a reference like this, but now work:

///<reference path="types/test.d.ts"/>

Of course, I don't want to include this declare file in every file. Is there a way to enable the declare in whole project?

I don't know how VSCode works with typescript. Maybe I just make a mistake in config file.

like image 309
Finn Avatar asked Sep 05 '25 17:09

Finn


1 Answers

typeRoots refers to directories, not files. Plus, it refers to the containing folder of types packages.

A types package is a folder with a file called index.d.ts or a folder with a package.json that has a types field. - typescriptlang.org

Typically this is the ./node_modules/@types folder, which is also the default value of typeRoots option.

For your case, it's better to use the include option instead of typeRoots.

{
  "include": [
    "./types",
    /* other .ts or .d.ts source code containing folders here */
  ],
  "compilerOptions": { ... }
}
like image 125
hackape Avatar answered Sep 07 '25 18:09

hackape