Javascript Type
typeof and instanceof are both operators in JavaScript that are used to check the type of a value or an object. However, they work differently and have different use cases.
typeof
Returns a string indicating the type of an operand.
typeof "Hello World" // => "string"
typeof 42 // => "number"
typeof true // => "boolean"
typeof undefined // => "undefined"
typeof null // => "object"
typeof [1, 2, 3] // => "object"
typeof { name: "John", age: 30 } // => "object"
Note:
typeof null
returns"object"
, which is a known quirk of JavaScript. This is becausenull
is considered an empty object reference in JavaScript.
instanceof
Checks if an object is an instance of a particular class.
var today = new Date();
today instanceof Date // => true
today instanceof Object // => true
var names = ["John", "Paul", "George", "Ringo"];
names instanceof Array // => true
names instanceof Object // => true
var person = { name: "John", age: 30 };
person instanceof Object // => true
person instanceof Array // => false
In the above example,
today
is an instance of theDate
class,names
is an instance of theArray
class, andperson
is an instance of theObject
class.
keyof
The keyof
operator is used in TypeScript to get a union of all the keys of an object type. It returns the names of properties of a given object type.
type Person = {
name: string;
age: number;
isEmployed: boolean;
};
// keyof Person would be the union of the property names:
type PersonKeys = keyof Person; // => "name" | "age" | "isEmployed"
Useful when you need to enforce that a variable or argument corresponds to a key in an object, helping improve type safety in TypeScript.
function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person: Person = { name: "John", age: 30, isEmployed: true };
// Valid keys
const name = getValue(person, "name"); // => "John"
const age = getValue(person, "age"); // => 30
// Invalid key
// const invalid = getValue(person, "invalidKey"); // Error: Argument of type '"invalidKey"' is not assignable to parameter of type '"name" | "age" | "isEmployed"'
Note:
keyof
is only available in TypeScript and helps you enforce correct key names when accessing object properties.