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:
- Interfaces are purely compiled time construct
- Are useful for documenting and validating the required shape of properties.
- An interface may optionally have a type parameter
- An interface with type parameter is called generic interfaces.
- An interface cannot declare a property with the same name as an inherited private property.
Category: Software
Tags: TypeScript