Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active May 10, 2019 16:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OliverJAsh/381cd397008309c4a95d8f9bd31adcd7 to your computer and use it in GitHub Desktop.
Save OliverJAsh/381cd397008309c4a95d8f9bd31adcd7 to your computer and use it in GitHub Desktop.
TypeScript object types

JS terminology

  • "primitive": boolean, number, string, symbol, null, undefined
  • "object" aka "non-primitive": any "custom object" (e.g. { foo: 1 }) or function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types

(In JS, people mistakingly think of primitives as "object"s, but in strict JS terminology, they're not.)

object type

An "object" aka "non-primitive" (as per JS terminology above).

const myObject: object = primitive // error
const myObject: object = customObjectOrFunction // no error

Object type

The class instance behind any "object".

primitive instanceof Object // false
customObjectOrFunction instanceof Object // true

// At first glance, we would expect this to error, so that TS' behaviour matches
// JS's runtime behaviour. However, TS only cares about structures, so this does
// not error.
const myObject: Object = primitive;

const myObject: Object = customObjectOrFunction;

// Note: `Object` value === `ObjectConstructor` type

{} aka "empty object type"

An object but specifically one without any properties (TODO: correct?).

const myObject: {} = {}; // no error

// At first glance, we would expect this to error, but it doesn't. TODO: why?
const myObject: {} = { foo: 1 };

Related

@OliverJAsh
Copy link
Author

@RyanCavanaugh Just to check my understanding, is this type hierarchy diagram correct?

object   non-nullable primitive   null   undefined
------------- {} --------------
-------------------- unknown ---------------------

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment