Interface declarations in TypeScript

TypeScript allows us to define complex types via interfaces. Interfaces play a very important role in complex scenarios. for example when objects contain other properties. In regular form, defining an interface is a little bit like the C# syntax and implementing an interface members by a class is in the below form:


  1. interface IBaseInterface {
  2.     GetSomthing();
  3. }
  5. class BaseClass implements IBaseInterface {
  7.     GetSomthing() {
  8.     }
  9. }


You can define generic types in TypeScript like C# as well: 


  1. interface IFoo2<T, U> {
  3.     Action<T, U>();
  4. }
  7. interface IFoo3<T, U> {
  8.     Action<T, U>(): IFoo2<T, U>;
  9. }


Defining an output of the methods in interfaces and also the type of properties are very cool:


  1. interface IMachine {
  2.     SpeedTest(): string;
  3.     Color: string;
  4. }


And in the case of implementing the IMachine members you have to return a value (string in this case) in SpeedTest():


  1. class Machine implements IMachine {
  2.     Color: string;
  3.     public SpeedTest() {
  4.         return "String!";
  5.    }



Notes about interfaces:

  1. Interfaces are purely compile time construct
  2. Are useful for documenting and validating the required shape of properties.
  3. An interface may optionally have type parameter
  4. An interface with type parameter is called generic interfaces.
  5. An interface cannot declare a property with the same name as an inherited private property.

Tags: TypeScript

comments powered by Disqus