-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Description
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:
- if
instance instanceof Class
is true, then returntrue
- if
instance.constructor.name
is the same as theClass.name
, then returntrue
- 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