skip to Main Content

Consider this example

// ../folder/outside/root/index.ts
import { Client } from 'discord.js';

export class Something {
    constructor(public client: Client) {
        console.log(client instanceof Client); // logs false
    }
}

// main.ts
import { Client } from 'discord.js';
import { Something } from '../folder/outside/root/index.ts';

const client = new Client({ intents: [...] }); // intents can be anything

console.log(client instanceof Client) // logs true

const something = new Something(client);

if you move the folder "../folder/outside/root/index.ts" into the root folder of "main.ts", it logs true

CONTEXT

I’m publishig my npm package, discord-debug, and while testing it locally, it works well. But when I install it via npm or an external folder, it throws the following error:

throw new TypeError('`client` must be a discord.js Client instance');
            ^

TypeError: `client` must be a discord.js Client instance

Which is defined in this line

Since the error doesn’t cover much of the issue, it really is a hard task figuring it out and fixing it.

2

Answers


  1. Look the Client class signature

    class Client<Ready extends boolean = boolean> extends BaseClient
    

    Example:

    class BaseClient {
        version = 1
    }
    
    export class Client extends BaseClient {
        race = "human"
    }
    
    export class AnotherClient extends BaseClient {
        race = "human"
    }
    
    
    export function verifyClientInstance(arg: Client) {
        if (!(arg instanceof Client)) {
            console.log('not an instance')
        } else {
            console.log('instance')
        }
    }
    
    export const client = new Client()
    
    export const anotherClient = new AnotherClient()
    
    
    verifyClientInstance(client) // log is "instance"
    verifyClientInstance(anotherClient) // log is "not an instance"
    

    What may be happening is that an instance is being passed that extends from BaseClient that is not Client and has the same properties as the same (Client)

    Login or Signup to reply.
  2. Assuming the two directories have separate node_modules folders, it’s correct that instanceof returns false, because instanceof checks that the class is somewhere in the instance’s prototype chain via reference equality. You’ll hit similar issues with real-world usage of your library if the consuming code happens to use a different version of the discord library. For that reason, it’s typically better for library code to use duck typing for any necessary type checks that rely on external dependencies (or simply rely on TypeScript + documentation and don’t check at runtime at all).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search