Interfaces allow you to construct the shape of certain implementation. Interfaces should not really be a new concept to you considering your background in .NET, and in TypeScript it is very much the same.
Interfaces are defined using the keyword interface
, as follows:
enum Operand { Sum, Subtract, Multiply, Divide } interface Calculable { left: number; right: number; operand: Operand; }
Furthermore, interfaces support optional members and read-only properties, too:
interface Calculable { readonly left: number; readonly right: number; operand?: Operand; }
In the preceding example, the Calculable
interface has two readonly
properties, left
and right
, as well as an optional operand
property. Read-only declarations can only be set when first initialized or inside the constructor of the owning class.
Like other interface-supporting languages, you can code a certain hierarchy of interfaces by extending them.