What's the difference between “declare class” and “interface” in TypeScript

后端 未结 4 2260
谎友^
谎友^ 2020-11-27 10:33

In TypeScript, when creating .d.ts source declaration files, which is preferable and why?

declare class Example {
    public Method(): void; 
}
4条回答
  •  佛祖请我去吃肉
    2020-11-27 11:29

    Difference between declare and interface in TS:

    declare:

    declare class Example {
        public Method(): void; 
    }
    

    In the above code declare lets the TS compiler know that somewhere the class Example is declared. This does not mean that the class is magically included. You as a programmer are responsible for having the class available when you are declaring it (with the declare keyword).

    interface:

    interface Example {
        Method(): void;
    }
    

    An interface is a virtual construct that only exists within typescript. The typescript compiler uses it for the sole purpose of type checking. When the code is compiled to javascript this whole construct will be stripped out. The typescript compiler uses interfaces in order to check if objects have the right structure.

    For example when we have the following interface:

    interface test {
      foo: number,
      bar: string,
    }
    

    The objects which we define which have this interface type need to match the interface exactly:

    // perfect match has all the properties with the right types, TS compiler will not complain.
      const obj1: test = {   
        foo: 5,
        bar: 'hey',
      }
    

提交回复
热议问题