Skip to content

Create a looseInstanceOfClass to check FileBox and Puppet instances #2090

@huan

Description

@huan

When we are using the instanceof operator to check whether an instance is a Class, the instance must be exactly created by that Class, or instanceof will return false.

For example, if we created a fileBox with file-box@0.1, then we want to know whether the fileBox is the instance of the module file-box, but with the different version, say, file-box@0.2, then the instanceof will return false.

Sometimes we just want to know whether the instance is from this module, we do not care about the version. That's the reason why we want to introduce the looseInstanceOf method.l

looseInstanceOfClass

For given instance and Class, This method only does two checks:

  1. if instance instanceof Class is true, then return true
  2. if instance.constructor.name is the same as the Class.name, then return true
  3. else return false

Abstract Class & Private Constructor

If a class is an abstract class or the constructor is private, then we will not be able to infer the { new (...args: any): T } as expected.

The workaround is:

const looseInstanceOfFileBox = looseInstanceOfClass(FileBox as any as FileBox & { new (...args: any): FileBox })
const looseInstanceOfPuppet = looseInstanceOfClass(Puppet as any as Puppet & { new (...args: any): Puppet })

That's it!

We will use it to check the FileBox and Puppet in Wechaty.

Resolve: #1930

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions