Typescript files
PgTyped also supports parsing queries from TS files.
Such queries must be tagged with an sql
template literal, like this:
PgTyped will then scan your project for such sql
tags and generate types for each query, saving the types in a filename.types.ts
file.
Once the type files have been generated you can import them to type your query:
#
ExpansionsTemplate literals also support parameter expansions. Here is how a typical insert query looks like using SQL-in-TS syntax:
Here $$users(name, age)
is a parameter expansion.
#
Expansions in SQL-in-TS queries#
Array spreadThe array spread expansion allows to pass an array of scalars as parameter.
#
Syntax:#
Example:Query code:
Resulting query:
#
Object pickThe object pick expansion allows to pass an object as a parameter.
#
Syntax:#
Example:Query code:
Resulting query:
#
Array spread and pickThe array spread-and-pick expansion allows to pass an array of objects as a parameter.
#
Syntax:#
Example:Resulting query:
#
Parameter type referenceExpansion | Syntax | Parameter Type |
---|---|---|
Scalar parameter | $paramName | paramName: ParamType |
Object pick | $paramName(name, author) | paramName: { name: NameType, author: AuthorType } |
Array spread | $$paramName | paramName: Array<ParamType> |
Array pick and spread | $$paramName(name, author) | paramName: Array<{ name: NameType, author: AuthorType }> |
#
Substitution referenceExpansion | Query in TS | Query with substituted parameter |
---|---|---|
Simple parameter | $parameter | $1 |
Object pick | $object(prop1, prop2) | ($1, $2) |
Array spread | $$array | ($1, $2, $3) |
Array pick and spread | $$objectArray(prop1, prop2) | ($1, $2), ($3, $4), ($5, $6) |