An interface is a way to take a particular structure/shape and give it a name so that we can reference it later as a type. It defines a contract within our code. Interfaces begin with the keyword interface. Let's take an example:
interface Person {
name: string
children?: number
isMarried(): boolean
(): void
}
The specified interface Person has the following:
- The name property of type string.
- The optional property children of type number. Optional properties are denoted by a question mark and can be omitted.
- The isMarried method that returns a boolean value.
- Anonymous (unnamed) method that returns nothing.
Typescript allows you to use the syntax [index: type] to specify a string or number type based collection of key/value pairs. Interfaces perfectly fit such data structures. For example, consider the following syntax:
interface Dictionary {
[index: number]: string
}
Beside interfaces, there are classes that describe objects. A class acts as a template for instantiating specific objects. The syntax for TypeScript's classes is almost identical to that of native classes in ECMAScript 2015 with some handy additions. In TypeScript, you can use public, private, protected, and readonly access modifiers:
class Dog {
private name: string; // can only be accessed within this class
readonly owner: string = "Max"; // can not be modified
constructor(name: string) {this.name = name;}
protected sayBark() { }
}
let dog = new Dog("Sam");
dog.sayBark(); // compiler error because method 'sayBark' is protected and
// only accessible within class 'Dog' and its subclasses.
Members with omitted modifiers are public by default. If a property or method is declared with the static keyword, there is no need to create an instance to access them.
A class can be abstract, that means, it may not be instantiated directly. Abstract classes begin with the keyword abstract. A class can implement an interface as well as extend another class. We can achieve that using the implements and extends keywords, respectively. If a class implements some interface, it must adopt all properties from this interface; otherwise, you will get an error about missing properties:
interface Animal {
name: string;
}
class Dog implements Animal {
name: string;
// do specific things
}
class Sheepdog extends Dog {
// do specific things
}
It is possible to declare a constructor parameter with a modifier. As result, a member will be created and initialized in one place:
class Dog {
constructor(private name: string) { }
// you can now access the property name by this.name
}
The last basic type to be mentioned here is enum. Enums allow us to define a set of named constants. Enum members have numeric values associated with them (started with 0):
enum Color {
Red,
Green,
Blue
}
var color = Color.Red; // color has value 0