-
Notifications
You must be signed in to change notification settings - Fork 280
/
infer-result.ts
54 lines (52 loc) · 1.47 KB
/
infer-result.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { DeleteResult } from '../query-builder/delete-result.js'
import { InsertResult } from '../query-builder/insert-result.js'
import { UpdateResult } from '../query-builder/update-result.js'
import { CompiledQuery } from '../query-compiler/compiled-query.js'
import { Compilable } from './compilable.js'
/**
* A helper type that allows inferring a select/insert/update/delete query's result
* type from a query builder or compiled query.
*
* ### Examples
*
* Infer a query builder's result type:
*
* ```ts
* import { InferResult } from 'kysely'
*
* const query = db
* .selectFrom('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .select(['person.first_name', 'pet.name'])
*
* type QueryResult = InferResult<typeof query> // { first_name: string; name: string; }[]
* ```
*
* Infer a compiled query's result type:
*
* ```ts
* import { InferResult } from 'kysely'
*
* const compiledQuery = db
* .insertInto('person')
* .values({
* first_name: 'Foo',
* last_name: 'Barson',
* gender: 'other',
* age: 15,
* })
* .returningAll()
* .compile()
*
* type QueryResult = InferResult<typeof compiledQuery> // Selectable<Person>[]
* ```
*/
export type InferResult<C extends Compilable<any> | CompiledQuery<any>> =
C extends Compilable<infer O>
? ResolveResult<O>
: C extends CompiledQuery<infer O>
? ResolveResult<O>
: never
type ResolveResult<O> = O extends InsertResult | UpdateResult | DeleteResult
? O
: O[]