Home > Software engineering >  how to add a new property to the existing type with d.ts in Typescript?
how to add a new property to the existing type with d.ts in Typescript?

Time:01-05

in my src/router.ts

export function resetRouter() {
    router.matcher = createRouter().matcher 
    // Property 'matcher' does not exist on type 'VueRouter'. Did you mean 'match'?
}

i create a src/router.d.ts and write some code:

import 'vue-router'

declare module 'vue-router' {
    class VueRouter {
        matcher: any
    }
}

but this doesn't work, the error still exist

here is node_modules/vue-router/index.d.ts file

export declare class VueRouter {
  constructor(options?: RouterOptions)

  app: Vue
  options: RouterOptions
  mode: RouterMode
  currentRoute: Route

  beforeEach(guard: NavigationGuard): Function
 ...

so how to fix this ?

CodePudding user response:

You're talking about declaration merging, where you can add another declaration with the same name as an existing one, and the compiler will merge them into a single definition. And, as you've seen, it is disallowed to merge two class declarations together.

Luckily, you are allowed to merge an interface with the instance side of a class declaration:

// existing class declaration
class Foo {
  a: string = "a";
  b: string = "b";
}

// merge another property into the type named Foo
interface Foo {
  z: string
}

// test it out
const f = new Foo();
f.z = "hello"; // okay
console.log(f.z.toUpperCase()); // "HELLO"

Note that declaration merging doesn't have any effect at runtime, so if you merge an added property into the class type, you also need to write code to add the property at runtime also, otherwise you can hit runtime problems:

const g = new Foo();
g.z.toUpperCase(); // no compiler error, but
//            
  • Related