Blog

Filter posts by Category Or Tag of the Blog section!

Interface declarations in TypeScript

Sunday, 23 March 2014

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 member by a class is in the below form:

interface IBaseInterface {

    GetSomthing();

}

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


interface IFoo2<T, U> {



    Action<T, U>();

}





interface IFoo3<T, U> {

    Action<T, U>(): IFoo2<T, U>;

}

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


interface IMachine {

    SpeedTest(): string;

    Color: string;

}

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


class Machine implements IMachine {

    Color: string;

    public SpeedTest() {

        return "String!";

   }

Notes about interfaces:

  1. Interfaces are purely compiled time construct
  2. Are useful for documenting and validating the required shape of properties.
  3. An interface may optionally have a 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.

Category: Software

Tags: TypeScript

comments powered by Disqus