typescript interface initialization

前端 未结 3 2046
抹茶落季
抹茶落季 2020-12-23 19:31

My level of typescript is \'ABSOLUTE BEGINNER\' but I have a good OOP background. I am building an with typescript that reference an external t.ds library that

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 20:30

    • You can't create an instance of an interface since Typescript doesn't "translate" it into js. You can check the js that is created and you will see nothing in it. It's simple for compile errors, type safety and intelisense.

      interface IStackOverFlow
      {
         prop1 : string;
         prop2 : number;
      }
      
      public MyFunc(obj : IStackOverFlow)
      {
          // do stuff
      }
      
      var obj = {prop1: 'str', prop2: 3};
      MyFunc(obj); // ok
      
      var obj2 = {prop1: 'str'};
      MyFunc(obj); // error, you are missing prop2
      
      // getObj returns a "any" type but you can cast it to IStackOverFlow. 
      // This is just an example.
      var obj =  getObj();
      

提交回复
热议问题