Kay
Kay7mo ago

Check if class instance is instance of provided type

I have a function that dynamically loads a folder with ts files, initiates the classes in them and saves them. The function takes in a type for its return type like this load<T extends BaseInteraction>. But when i use DynamicClass instanceof T it says 'T' only refers to a type, but is being used as a value here.. is there a way to compare the class to the provided class?
2 Replies
Deno AI Helper
Deno AI Helper7mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the information you've provided, it seems like you're trying to use a generic type parameter T as a value in a runtime check with instanceof. In TypeScript, which Deno uses, type parameters like T are used for static type checking and do not exist at runtime, which is why you're seeing the error 'T' only refers to a type, but is being used as a value here. One way to work around this issue is to pass the class constructor itself as an argument to your function, and then use that constructor in the instanceof check. Here's a conceptual example:
function load<T extends BaseInteraction>(classRef: { new(): T }): T {
// ... load and instantiate the class
let instance = new classRef();
if (instance instanceof classRef) {
// This will now work, as classRef is a value (the constructor function)
// and can be used with instanceof
}
return instance;
}
function load<T extends BaseInteraction>(classRef: { new(): T }): T {
// ... load and instantiate the class
let instance = new classRef();
if (instance instanceof classRef) {
// This will now work, as classRef is a value (the constructor function)
// and can be used with instanceof
}
return instance;
}
In this example, classRef is a constructor function for the class that extends BaseInteraction, and you can use it in the instanceof check. Please note that this advice is not based on the Deno documentation, and I would advise you to double-check the accuracy of this advice and ensure it fits the context of your application.
Leokuma
Leokuma7mo ago
Can you share the whole function code?

Did you find this page helpful?