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:
Expansions#
Template 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 spread#
The array spread expansion allows to pass an array of scalars as parameter.
Syntax:#
Example:#
Query code:
Resulting query:
Object pick#
The object pick expansion allows to pass an object as a parameter.
Syntax:#
Example:#
Query code:
Resulting query:
Array spread and pick#
The array spread-and-pick expansion allows to pass an array of objects as a parameter.
Syntax:#
Example:#
Resulting query:
Parameter type reference#
| Expansion | 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 reference#
| Expansion | 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) |