Separate a function’s type (contract) from its implementation
Like C/C++ header and source
Many people coming from C/C++ want something like .h + .cpp
user.decl.ts
export type GetUser = (id: number) => Promise<User>;
export interface User {
id: number;
name: string;
}
user.impl.ts
import { GetUser } from "./user.types";
export const getUser: GetUser = async (id) => {
return {
id,
name: "Alice",
};
};
Interface describing a module (Dependency Injection)
export interface UserService {
getUser(id: number): Promise<User>;
saveUser(user: User): Promise<void>;
}
export const userService: UserService = {
async getUser(id) {
return {
id,
name: "Alice",
};
},
async saveUser(user) {
console.log(user);
},
};
Declare function type once, implement many times
type Compare<T> = (a: T, b: T) => boolean;
const compareNumbers: Compare<number> = (a, b) => a === b;
const compareStrings: Compare<string> = (a, b) => a === b;