Greetings We have TypeScript 1.8

I write this:

var v: Object; v = {name1: 'val1'} 

Everything compiles well. It seems like Object is compatible with any object. I write like this:

 interface MyInterface { name2: string; } var v: MyInterface; v = {name1: 'val1', name2: 'val2'} // <--- РУГАЕТСЯ 

And he scolds: Error: (138, 55) TS2322: Type '{name1:' val1 ', name2:' val2 '}' is not assignable to type 'MyInterface'. Object literal may not specify the type of myInterface.

BUT! If only "known properties", then why not swear at the first option with Object? After all, in lib.d.ts, Object is also defined as an Interface:

 interface Object {... 

And, of course, no name1 is described there either.

    1 answer 1

    Ok, the question turned out to be more complicated. We look at the specification of the language , section 3.11.5. We read:

    If it’s not true, it’s true:

    • T is not an object, union, or intersection type.
    • T is an object type and
      • T has a property with the same name as P ,
      • T has a string or numeric index signature,
      • T has no properties, or
      • T is the global type 'Object'. (***)
    • T is a type of union or intersection of the type of constituent types.

    Thus, the special place of Object 'is directly stated in the specification, in the paragraph indicated by three asterisks. Also specially specified interface without properties.


    Example:

    This is compiled because Object :

     var v: Object; v = {name1: 'val1', name2: 'val2'} 

    This is not compiled because of the superfluous name1 property:

     interface MyInterface1 { name2: string; } var x1: MyInterface1; x1 = {name1: 'val1', name2: 'val2'} 

    This compiles because the interface has no properties:

     interface MyInterface2 { } var x2: MyInterface2; x2 = {name1: 'val1', name2: 'val2'} 

    This is not compiled, the name1 and name2 properties are superfluous, exceptions do not apply:

     interface MyInterface3 extends Object { } var x3: MyInterface3; x3 = {name1: 'val1', name2: 'val2'} 

    This is compiled since there is an index signature:

     interface MyInterface4 { [x: string]: any; } var x4: MyInterface4; x4 = {name1: 'val1', name2: 'val2'} 
    • Something is not right ... - Qwertiy
    • @Qwertiy: Why? - VladD
    • Therefore - Qwertiy
    • @Qwertiy: Taki-figured out :) - VladD