Sometimes your type annotations become really long, so you need some mechanisms which help you not repeat yourself. And prevent "copy-paste" errors.
Playground
const user: {email: string;password: string;} = { email: "test.email@gmail.com", password: "qwerty" };const copyOfOriginalUser: {email: string;password: string;} = user;//-------------------function createResponse(status: "Success" | "Failed"): { status: "Success" | "Failed" } {return { status };}
One of them is type alisases. Type aliases create a new name for a type.
Type aliases can be created using the keyword type
followed by its name, an equals sign =
, and a type definition. You can place any valid type definition after equals sign =
.
Playground
// Type alias for object typetype User = {email: string;password: string;};const user: User = { email: "test.email@gmail.com", password: "qwerty" };const copyOfOriginalUser: User = user;//-------------------// Type alias for union typetype Status = "Success" | "Failed";function createResponse(status: Status): { status: Status } {return { status };}
Aliasing doesn’t create a new type - it creates a new name to refer to source type.
Interfaces
Also you can use implements
with object type aliases for Class Types to tell Hegel that you want class to match "protocol".
Playground
type JsonSerializable = {toJSON: () => Object,...};class User implements JsonSerializable {email: string;password: string;constructor(email, password) {this.email = email;this.password = password;}toJSON() {return {email: this.email,password: this.password,_type: "User"};}}const json: JsonSerializable = new User("test@gmail.com", "qwerty");
Note, that your object type which should act like interface should be a soft object type.