Can't seem to be able to assert instances of string in Deno:
import {
assertInstanceOf
} from "https://deno.land/[email protected]/testing/asserts.ts";
assertInstanceOf( "foo", string );
Throws:
error: TS2693 [ERROR]: 'string' only refers to a type, but is being used as a value here.
assertInstanceOf( "foo", string );
~~~~~~
at file:///home/jmerelo/Code/my-stackoverflow-examples/js/string-assert.ts:6:26
Fair enough, let's try this
assertInstanceOf( "foo", String );
Now I'm confused:
Uncaught error from ./string-assert.ts FAILED
ERRORS
./string-assert.ts (uncaught error)
error: AssertionError: Expected object to be an instance of "String" but was "string".
Any idea of what would be the correct type here?
There's clearly a workaround here, to use typeof. But I would like to know what's the solution to this Catch-22
It's not a Catch-22, but a false premise. In JavaScript: while primitives do appear object-like in some aspects, they are not objects (see JavaScript data types and data structures) — therefore they are not useful operands for use with the
instanceofoperator because the evaluation will always befalse(see spec):For strings, this is explained further on MDN's
Stringarticle in the section String primitives and String objects.Below is a code example demonstrating how to discriminate and assert whether a value is a string literal or an object instance of
Stringusing Deno's standard testing library and user-defined type guard functions.TS Playground
module.ts:Output:
Compiled JavaScript with imports inlined: