Use instanceof for custom types:
var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false
Use typeof for simple built in types:
'example string' instanceof String; // false
typeof 'example string' == 'string'; // true
'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false
true instanceof Boolean; // false
typeof true == 'boolean'; // true
99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true
function() {} instanceof Function; // true
typeof function() {} == 'function'; // true
Use instanceof for complex built in types:
/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object
[] instanceof Array; // true
typeof []; //object
{} instanceof Object; // true
typeof {}; // object
And the last one is a little bit tricky:
typeof null; // object
Answer from Szymon Wygnański on Stack OverflowUse instanceof for custom types:
var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false
Use typeof for simple built in types:
'example string' instanceof String; // false
typeof 'example string' == 'string'; // true
'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false
true instanceof Boolean; // false
typeof true == 'boolean'; // true
99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true
function() {} instanceof Function; // true
typeof function() {} == 'function'; // true
Use instanceof for complex built in types:
/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object
[] instanceof Array; // true
typeof []; //object
{} instanceof Object; // true
typeof {}; // object
And the last one is a little bit tricky:
typeof null; // object
Both are similar in functionality because they both return type information, however I personally prefer instanceof because it's comparing actual types rather than strings. Type comparison is less prone to human error, and it's technically faster since it's comparing pointers in memory rather than doing whole string comparisons.
Difference Between typeof and instanceof in JavaScript | Interview Question
typescript - Typeof/instanceof type alias - Stack Overflow
If typescript is duck-typed, how come when you use "instanceof", typescript accurately separate out the individual classes that implement the same interface? And how can we take advantage of this functionality in our typing?
type .kind checks vs. class instanceof checks
Videos
Short answer
(Almost) all type information are removed after compilation, and you can't use instanceof operator with an operand (T in your example) that does not exist at runtime.
Long answer
An identifier in TypeScript could belong to one or more of the following groups: type, value, namespace. What gets emitted as JavaScript is identifiers in the group of value.
Thus runtime operators only works with values. So if you want to do runtime type checking of the value of foo, you'll need to do the hard work yourself.
See the Declaration Merging section of the TypeScript Handbook for more information.
To add to @vilcvane's answer: types and interfaces disappear during compilation, but some class information is still available. So, for example, this doesn't work:
interface MyInterface { }
var myVar: MyInterface = { };
// compiler error: Cannot find name 'MyInterface'
console.log(myVar instanceof MyInterface);
But this does:
class MyClass { }
var myVar: MyClass = new MyClass();
// this will log "true"
console.log(myVar instanceof MyClass);
However, it's important to note that this kind of test can be misleading, even when your code compiles with no errors:
class MyClass { }
var myVar: MyClass = { };
// no compiler errors, but this logs "false"
console.log(myVar instanceof MyClass);
This makes sense if you look at how TypeScript is generating the output JavaScript in each of these examples.
Edit: I know that instanceof checks at runtime, I'm very familiar with it and have been using it for many years. My question is specifically how the typing system works in typescript, how/why typescript is able to discern via type inference the difference between Error and PseudoError. And, given that it can, whether it is possible to leverage that kind of discernment to create a utility function that's based on this rather than based on shapes and interfaces.
In lib.es5.d.ts in typescript we have:
interface Error {
name: string;
message: string;
stack?: string;
}Now in my typescript file, if I create a new type, like this:
class PseudoError {
name = "hello"
message = "world"
stack? = "friends"
}And I do the following:
const test : PseudoError | Error = new PseudoError() type withoutError = Exclude<typeof test, Error> // <--- results to never, because of duck typing ?
The above is expected, because PseudoError and Error implement the same interface. So if I'm excluding Error, then I'm also excluding PseudoError by duck type standards.
But when I do this:
if (test instanceof Error) {
test // <--- hover over = Error
} else {
test // <--- hover over = PseudoError
}
It suggests that there is obviously some built-in functionality in typescript that doesn't work like in a duck-type-y way. This clearly aligns with the desired outcome in JS, but in my situation, I would like to have an Exclude<...> utility type that does the same thing as what typescript is doing behind the scenes with instanceof.
For example, where's this NotInstanceOf utility function?
const test : PseudoError | Error = new PseudoError() type withoutError = NotInstanceOf<typeof test, Error> // <--- results to PsuedoError