isA()
import { isA } from "@fed1/jsos";
This JSFunction is at the heart of both JSOS's type system and its
multimethods.
The isA function takes a value as its first argument and
(usually) a type as its second argument and returns a JSBoolean that indicates
whether the first argument has an is-a relationship witht he second argument.
Usage
isA(a, b)
Parameters
| # | Parameter | Required? | Type |
|---|---|---|---|
| 1 | a | yes | TAny |
| 2 | b | yes | TAny |
1. a
A value to be checked for whether or not it has an is-a relationship with b.
2. b
A TType, JS class or value to check a against.
Return value
A JSBoolean that is true if a is a b, otherwise false.
Examples
When used with JSOS types, the isA function recognizes both the type hierarchy
as well as tyoe-of relationships. Some examples:
isA(JSString, TJSType) // true because the type of JSString is TJSType
isA(JSNumber, TFloat) // true because JSNumber is a child of TFloat
isA(JSNumber, TReal) // true bceause JSNumber is an ancestor of TReal
isA(JSNumber, TAny) // true because everything is an ancestor of TAny
It also works with a JS value and a JSOS type:
isA("foo", JSString) // true because typeOf("foo") === JSString
isA(20, JSNumber) // true because typeOf(20) === JSNumber
isA(20n, JSNumber) // false because typeOf(20n) === JSBigInt
isA(20, TNumber) // true because JSNumber is an ancestor of TNumber
isA(20n, TNumber) // true because JSBigInt is an ancestor of TNumber
You can also use isA with JavaScript classes:
class Foo {}
class Bar extends Foo {}
const myFoo = new Foo();
const myBar = new Bar();
isA(myFoo, Foo) // true because myFoo was created with the Foo constructor
isA(myFoo, Bar) // false because Bar is a sub class of Foo
isA(myBar, Bar) // true because myBar was created with the Bar constructor
isA(myBar, Foo) // true because myBar ia a Bar which is a sub class of Foo
isA(Foo, Bar) // false because Foo is not a sub class of Bar
isA(Bar, Foo) // true because Bar is a sub class of Foo
If the second argument is itself a value, isA returns true only if a and b
are identical:
isA("foo", "foo") // true because strings are primitive values
isA(20, 20) // true because numbers are primitive values
isA({}, {}) // false because those are separate references
const o = {};
isA(o, o) // true because a and b point to the same object
Version History
| Feature | Since version |
|---|---|
| isA() | 1.0 |
See also
- API: typeOf
