Difference between 'object' and {} in TypeScript

后端 未结 2 1229
情深已故
情深已故 2020-12-03 00:46

Trying to figure out the difference between these 2 types in TypeScript:

foo: object

and

bar: {}?


Exa

2条回答
  •  长情又很酷
    2020-12-03 01:24

    The following example shows how different types of object 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: {}; // or Object
    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 that we can tell:

    • {} which is the same as type Object is the least specific. You can assign objects, arrays and primitives to it.
    • object is more specific and is similar to { [key: string]: any }. You can assign objects and arrays to it, but not primitives.
    • { [key: string]: string } is the most specific, that doesn't allow any primitive types, arrays or objects with a non-string value to be assigned to it.

    Link to TypeScript playground

提交回复
热议问题