Object Types

Introduction

TypeScript offers three object types:

  • {}, which can be called the anything that is non-null and non-undefined type. TODO: Find the official docs on that type.

  • object

  • Object

Because these types are very generic, using more specific types is recommended. That is, instead of, for example, object, try to use a type which specify the properties more precisely.

We should almost never use {} or Object. object is sometimes acceptable when no other more specific type seems to make sense.

{} is a ban-type in default eslint. Check ban-types on ESLint documentation.

Non-null and non-undefined type {}

The _non-null and non-undefined type {} allows any value of any type (literal or compound) as long the values are not null or undefined.

These are all valid:

var x: {} = 1;
var y: {} = "TS";
var f: {} = function fn() { return 1; };
var v: {} = {};
var w: {} = { lang: "TypeScript" };
var a: {} = [];
var b: {} = [1, "two", { three: 0b0011 }];
// etc.

But this is illegal:

var n: {} = null;
// ~ Type 'null' is not assignable to type '{}'.

var u: {} = undefined;
// ~ Type 'undefined' is not assignable to type '{}'.

The type {} accepts the set of all values of all types (not only compound types, but also literal types) except null and undefined.

object type

The object type (with lowercase “o”) allows for values of compound types (but no literals). Compound types include arrays, maps, sets, functions, classes or any value which is not a primitive.

These are all valid:

var v: object;
v = {};
v = { name: "Aayla Secura" };
v = function f() {};
v = class Lara {};
v = [];
v = [1, "two", { three: 0b0011 }];
v = new Set();
v = new Map();
v = () => undefined;
v = /regexp/i;

Remember that functions have Object as their prototype, so it should not come as a surprise that a function can be assigned to an identifier of type object.

But these produce type errors:

var a: object = undefined;
var b: object = null;
var c: object = 0xff;
var d: object = "two";
var e: object = Symbol("a-symbol");
var f: object = false;

Object type

Object used as a type allows for all values whose prototype is Object, which means every primitive and compound types.

Because Object is an interface in TypeScript, it requires a toString() method which returns some string.

var o: Object = {
  toString() {
    return null;
    // ~ Type '() => null' is not assignable to
    // ~ type '() => string'.
  },
};

Our toString() is returning a value which is not a string, therefore, it doesn’t satisfy the Object interface and a type error is produced. If we return any string from that method, then it type-checks.