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
`postgres` has TypeScript support. You can pass a row list type for your queries in this way:
127
+
```ts
128
+
interfaceUser {
129
+
id:number
130
+
name:string
131
+
}
132
+
133
+
const users =awaitsql<User[]>`SELECT * FROM users`
134
+
users[0].id// ok => number
135
+
users[1].name// ok => string
136
+
users[0].invalid// fails: `invalid` does not exists on `User`
137
+
```
138
+
139
+
However, be sure to check the array length to avoid accessing properties of `undefined` rows:
140
+
```ts
141
+
const users =awaitsql<User[]>`SELECT * FROM users WHERE id = ${id}`
142
+
if (!users.length)
143
+
thrownewError('Not found')
144
+
returnusers[0]
145
+
```
146
+
147
+
You can also prefer destructuring when you only care about a fixed number of rows.
148
+
In this case, we recommand you to prefer using tuples to handle `undefined` properly:
149
+
```ts
150
+
const [user]: [User?] =awaitsql`SELECT * FROM users WHERE id = ${id}`
151
+
if (!user) // => User | undefined
152
+
thrownewError('Not found')
153
+
returnuser// => User
154
+
155
+
// NOTE:
156
+
const [first, second]: [User?] =awaitsql`SELECT * FROM users WHERE id = ${id}`// fails: `second` does not exist on `[User?]`
157
+
// vs
158
+
const [first, second] =awaitsql<[User?]>`SELECT * FROM users WHERE id = ${id}`// ok but should fail
159
+
```
160
+
161
+
All the public API is typed. Also, TypeScript support is still in beta. Feel free to open an issue if you have trouble with types.
162
+
123
163
#### Query parameters
124
164
125
165
Parameters are automatically inferred and handled by Postgres so that SQL injection isn't possible. No special handling is necessary, simply use JS tagged template literals as usual.
0 commit comments