Skip to main content

One post tagged with "java"

View All Tags

Testing class compatibility with isAssignableFrom

· 4 min read
Simon Porritt
JsPlumb Development

Classes are a controversial topic in the Javascript/Typescript world. Are they a terrible idea? Are they really useful, when used sensibly? This post will make no attempt at answering either of these questions. This post is about a niche method that I first encountered many years ago in the world of Java - isAssignableFrom - and how you can go about writing it for use in Typescript/Javascript.

What does it do?

This is what the Javadocs have to say about it:

public boolean isAssignableFrom(Class<?> cls)

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false.

So, given some class, you can use isAssignableFrom to figure out whether that class is a subclass of some other class.

Why would I need this?

If you're thinking it's a bit niche, yes, I agree. isAssignableFrom is one of those methods you don't use much. But when you need it, you need it.