TypeScript: Type Aliases, Interfaces, and Advanced Features
Type Aliases
Type aliases allow you to define a more meaningful name for a type, enabling better readability and reuse.
Features of Type Aliases:
- Define meaningful names for types.
- Declare the shape of a type in one place and reuse it.
- Easily import and export types.
- Store any type, including primitives, objects, unions, or intersections.
- Create type aliases even inside functions.
Example:
type Amount = {
value: number;
currency: string;
};
function printAmount(amount: Amount) {
console.log(amount);
console.log(amount.value);
console.log(amount.currency);
}
printAmount({ value: 100, currency: "USD" });
Inheritance with Type Aliases:
type SpecialDate = Date & { getDescription: () => string };
const specialDate = Object.assign(new Date(), {
getDescription() {
return `The current date is ${this}`;
},
});
console.log(specialDate.getDescription());
Interfaces
Features of Interfaces:
- Interfaces cannot model all types in TypeScript (e.g., unions are not supported).
- Interfaces are better for extension and can extend other interfaces or be implemented by classes.
- Classes can implement interfaces to enforce structure.
- Interfaces are open (can be redeclared and merged).
Example:
interface Animal {
isAlive: () => boolean;
}
interface Mammal extends Animal {
hasHair: boolean;
}
class Dog implements Animal {
isAlive() {
return true;
}
}
Open Nature of Interfaces:
interface Promise<T> {
wow: () => void;
}
new Promise(() => {}).wow();
Recursive Types
Recursive types allow defining self-referential types.
Example:
type NestedNumber = number | NestedNumber[];
const val: NestedNumber = [1, [2, [3, [4]]]];
Question: Define a Type for JSON
A valid JSON value must be one of the following:
- Object
- Array
- String
- Number
- Boolean
- Null
JSONValue Type:
type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue };