You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Item 58: Consider Codegen as an Alternative to Complex Types
Things to Remember
While type-level TypeScript is an impressively powerful tool, it's not always the best tool for the job.
For complex type manipulations, consider generating code and types as an alternative to writing type-level code. Your code generation tool can be written in ordinary TypeScript or any other language.
Run codegen and git diff on your continuous integration system to make sure generated code stays in sync.## Code Samples
asyncfunctiongetBooks(db: Database){constresult=awaitdb.query(`SELECT title, author, year, publisher FROM books`);returnresult.rows;}
asyncfunctiongetLatestBookByAuthor(db: Database,publisher: string){constresult=awaitdb.query(`SELECT author, MAX(year) FROM books GROUP BY author WHERE publisher=$1`,[publisher]);returnresult.rows;}
// books-queries.tsimport{sql}from'@pgtyped/runtime';constselectLatest=sql` SELECT author, MAX(year) FROM books GROUP BY author WHERE publisher=$publisher`;asyncfunctiongetLatestBookByAuthor(db: Database,publisher: string){constresult=awaitselectLatest.run({publisher},db);// ^? const result: any[]returnresult;}
// books-queries.types.ts/** Types generated for queries found in "books-queries.ts" *//** 'selectLatest' parameters type */exportinterfaceselectLatestParams{publisher: string;}/** 'selectLatest' return type */exportinterfaceselectLatestResult{author: string;year: number;}/** 'selectLatest' query type */exportinterfaceselectLatestQuery{params: selectLatestParams;result: selectLatestResult;}
// books-queries.tsimport{sql}from'@pgtyped/runtime';import{selectLatestQuery}from'./books-queries.types';exportconstselectLatestBookByAuthor=sql<selectLatestQuery>` SELECT author, MAX(year) FROM books GROUP BY author WHERE publisher=$publisher`;asyncfunctiongetLatestBookByAuthor(db: Database,publisher: string){constresult=awaitselectLatestBookByAuthor.run({publisher},db);// ^? const result: selectLatestResult[]returnresult;}