Why Class B can be compiled with Typescript (type monitoring), Class C cannot pass, and Class B is expected to fail compilation)

I hope that Class B cannot be compiled like Class C.
Class C compiles an error as follows:

Type "{ name: string; some: string; }" is not assignable to type "Info".
Object literal may only specify known properties, and "some" does not exist in type "Info".


    interface Info {
      name: string;
    }
    
    interface Person {
      info(): Info;
    }
    
    class B implements Person {
        info() {
            return {
                name: "li",
                some: "1",
            };
        }
    }
    
    class C {
        info():Info {
            return {
                name: "li",
                some: "1",
            };
        }
    }

class B implements Person {
    info():Info {
        return {
            name: "li",
            some: "1",
        };
    }
}

translate adult words, class B :

  • class B implements Person
  • Class B implements Person interface
  • The return value of B.info satisfies Info definition
  • {name: "li", some: "1"} satisfies the definition of {name: string}
  • through

class C :

  • info (): Info
  • The return value of info is Info
  • {name: "li", some: "1"} and {name: string} are not completely consistent
  • fail

I don't quite understand why I want B to fail to compile like C .

One of the core principles of
TypeScript is type checking on the structure that the value has. It is sometimes called "duck typing" or "structural subtyping".

it doesn't matter if you expect a variable of type Info to pass in one or two more attributes of the object. So B passing is one of the design goals of TypeScript.

what if it's because of something strange? If you must let B hang up, you can use the upstairs method.


class C can be compiled?

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b32d80-2b5c3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b32d80-2b5c3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?