Tom Oliver's profile picture
Tom Oliver

Its been a while since I did any data modelling in typescript.

TS
// An example of a user management system
// Define user status type, just an enum
type UserAccountStatus = "ACTIVE" | "DORMANT" | "DELETED"
// Define a base type
type BaseUser = { name: string; status: UserAccountStatus }
// Create concrete types using the base type
type ActiveUser = BaseUser & { status: "ACTIVE" }
type DormantUser = BaseUser & { status: "DORMANT" }
type DeletedUser = BaseUser & { status: "DELETED" }
type User = ActiveUser | DormantUser | DeletedUser
// Create the type of function we want to implement
// Make return type a promise because we talk to the DB
type DeleteUser = (user: ActiveUser | DormantUser) => Promise<DeletedUser>
// do a temporary implementation of the function
const deleteUser: DeleteUser = (user) => {
const deletedUser: DeletedUser = { ...user, status: "DELETED" }
// define a helper that we haven't got yet
return writeUserToDB(deletedUser)
}
// declare the type of the helper like so:
declare function writeUserToDB<A extends User>(user: A): Promise<A>

No Webmentions for this note yet!