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
Look the Client class signature
Example:
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)
Assuming the two directories have separate
node_modules
folders, it’s correct thatinstanceof
returnsfalse
, becauseinstanceof
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 thediscord
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).