Typescript Interfaces vs Type alias — how, where & when to use them
As you’ll peeps may already know TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is mainly used for developing both client-side and server-side Javascript applications.
Type definitions can be either in the form of interfaces or type aliases
What are they -
An interface declaration always introduces a named object type whereas a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
Simple examples of interface declaration with objects/functions -
interface Person {
first: string;
last: string;
age: number;
married: boolean; }interface SetNumber {(x: number, y: number): void;}
Examples of type aliases declaration with objects/functions & other types -
// object
type Animal {
name: string;
type: string;
legs: number;
pet: boolean; }type SetTypeNumber = (x: number, y: number) => void;// primitive
type Person = string;// object
type Person = { first: string; age: number; };
// union
type Creation = Animal | Person;
// tuple
type arrayData = [number, string];
Extensions — the following four categories are possible
Interface extends interface
interface Count { x: number; }
interface Point extends Count{ y: number; }
Type alias extends type alias
type typeCount = { x: number; };
type Point = typeCount & { y: number; };
Interface extends type alias
type interfaceTotal = { x: number; };
interface Point extends interfaceTotal { y: number; }
Type alias extends interface
interface Total { x: number; }
type Point = Total & { y: number; };
Implementations — can be done using both interfaces, type alias & vice versa
interface Count {
x: number;
y: number;
}
class Totalcount implements Count {
x = 1;
y = 2;
}
type Count2 = {
x: number;
y: number;
};
class TotalCount2 implements Count2 {
x = 1;
y = 2;
}// but a type based union cannot be extended or implemented
type BothCounts = { x: number; } | { y: number; };
Merging declarations — is only possible with interfaces
// below code is similar to interface Point { x: number; y: number;}
interface Total { x: number; }
interface Total { y: number; }
const point: Total = { x: 1, y: 2 };
Thank you for the read, looking forward to some TS modifications in the near future in terms of usage with React JS