typescriptnuxt-auth

Typescript: Override property type from library - got error Subsequent property declarations must have the same type


I want to override property type from library declaration, i try to override using interface but i got error Subsequent property declarations must have the same type. How should i do to solve this issue?

// this is library declaration
declare class Auth {
    user: Record<string, string | number> | null 
    // i want to remove null type in user property, because i dont want to use `non-null assertion` in line 21
    // i cant change this file because it is 3rd party library
}

// ------------------------------

// our file

// my override interface, but fail
interface Auth {
    user: Record<string, string | number>
}

const a: Auth = {
    user: {
        name: 'joko',
        age: 30
    }
}

const userName = a.user!.name
// const userName = a.user.name // <-- i want use like this, because i'm sure that this property is always available

I've tried to override library decalaration using interface but it fail. My expected result is the type can be overriden without touching or change the library, only by using our code.


Solution

  • I have solved by my self. In my case, i want to override Auth interface on nuxt-auth module. Here is the solution:

    1. Duplicate modules types from node_modules, to our type file. Then change the appropriate interface (change Auth to IAuth). IAuth is our modified interface.
    import { IAuth } from '~/interface/auth/model';
    
    export * from '@nuxtjs/auth-next/dist';
    
    declare module 'vue/types/vue' {
      interface Vue {
        $auth: IAuth;
      }
    }
    
    // rest of the file
    
    1. Add file above as paths in tsconfig.json, so typescript will use that file instead of original module types.
    "compilerOptions": {
    // ...
    "paths": {
        "@nuxtjs/auth-next": [
            "types/nuxt-auth.d.ts"
          ],
        // ...  
       }
    // ...
    }
    

    Voila, the type is run as expected using our modified interface