Difference between "object" and {} in TypeScript

Trying to figure out the difference between the two types in TypeScript:

foo: object

and

bar: {} ?


Example: trying to assign object variable that is supposed to process the header information for the request:

 headers: object; 

Error results:

The type 'object' is not assigned to '{[key: string]: string} `.

The same condition holds if headers: {} , which leads to the conclusion that {} has somewhat less stringent requirements.

+16
source share
2 answers

In essence, TypeScript has three intricate types: Object , {} and object .

object Contains material that is present in all JavaScript objects. Any value (primitive, not primitive, zero, etc.) can be assigned the type Object .

{}

{} is an empty object. This is the same as Object .

an object

object was introduced in TypeScript 2.2 . This is any non-primitive type . You cannot assign it any primitive type, for example bool , number , string , symbol , null and undefined

Thus, if you try this:

 var strictTypeHeaders: { [key: string]: string } = {}; // non-primitive type var header: object = {}; header = strictTypeHeaders; // its OK strictTypeHeaders = header; // causes error "Type 'object' is not assignable to type '{ [key: string]: string }'" 

You will get a compilation error in the last line. This is because the type { [key: string]: string } more specific than the type object . There is no error in header = strictTypeHeaders , since both types are not primitive, and object is a more common type than { [key: string]: string }

+15
source

The following example shows how different types of objects behave differently:

 var o: object; o = { prop: 0 }; // OK o = []; // OK o = 42; // Error o = "string"; // Error o = false; // Error o = null; // Error o = undefined; // Error var p: {}; p = { prop: 0 }; // OK p = []; // OK p = 42; // OK p = "string"; // OK p = false; // OK p = null; // Error p = undefined; // Error var q: { [key: string]: any }; q = { prop: 0 }; // OK q = []; // OK q = 42; // Error q = "string"; // Error q = false; // Error q = null; // Error q = undefined; // Error var r: { [key: string]: string }; r = { prop: 'string' }; // OK r = { prop: 0 }; // Error r = []; // Error r = 42; // Error r = "string"; // Error r = false; // Error r = null; // Error r = undefined; // Error 

With this we can say:

  • {} , which matches the type of Object , is the least specific. You can assign objects, arrays and primitives to it.
  • object more specific and similar to { [key: string]: any } . You can assign objects and arrays to it, but not primitives.
  • { [key: string]: string } is the most specific one, which does not allow you to assign any primitive types, arrays or objects with non-string values ​​to it.
0
source

Source: https://habr.com/ru/post/1276057/


All Articles