object Type Annotations Exclude Primitives

Restrict a parameter to non-primitive values with the lowercase object type, and see why the older Object and {} annotations still accept strings.

TypescriptData Integrity

Code

typescriptsnippet
15 lines
// The lowercase object type accepts anything that is not a primitive
function describe(value: object): string {
  return 'keys: ' + Object.keys(value).length;
}

console.log(describe({ id: 7 }));
console.log(describe([1, 2, 3]));
console.log(describe(new Map([['a', 1]])));

// Primitives fail compilation against object:
// describe('text'), describe(42) and describe(null) are all rejected

// The older Object (capital) annotation is permissive and still accepts strings
const loose: Object = 'still allowed';
console.log('Object (capital) accepted a string:', typeof loose === 'string');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

keys: 1
keys: 3
keys: 0
Object (capital) accepted a string: true

Inside the code

object Type Annotations Exclude Primitives is built around the function describe.

Points of care

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

Signature: function describe(value: object)

Output lines are prefixed (Object (capital) accepted a string:), making each step’s effect easy to spot.

Key statements

return 'keys: ' + Object.keys(value).length;

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `describe` at load time.