Skip to content

Commit be03b0a

Browse files
committed
Improve types for and and or conditional operators
Closes #2120.
1 parent e8e6edf commit be03b0a

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

drizzle-orm/src/sql/expressions/conditions.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ import {
1414
View,
1515
} from '../sql.ts';
1616

17+
type SqlOrUndefined<T extends (SQLWrapper | undefined)[]> =
18+
T[number] extends undefined ? undefined : SQL;
19+
1720
export function bindIfParam(value: unknown, column: SQLWrapper): SQLChunk {
1821
if (
1922
isDriverValueEncoder(column)
@@ -101,27 +104,26 @@ export const ne: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {
101104
* )
102105
* ```
103106
*/
104-
export function and(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;
105-
export function and(
106-
...unfilteredConditions: (SQLWrapper | undefined)[]
107-
): SQL | undefined {
107+
export function and<T extends (SQLWrapper | undefined)[]>(
108+
...unfilteredConditions: T
109+
): SqlOrUndefined<T> {
108110
const conditions = unfilteredConditions.filter(
109-
(c): c is Exclude<typeof c, undefined> => c !== undefined,
111+
(c) => c !== undefined,
110112
);
111113

112114
if (conditions.length === 0) {
113-
return undefined;
115+
return undefined as SqlOrUndefined<T>;
114116
}
115117

116118
if (conditions.length === 1) {
117-
return new SQL(conditions);
119+
return new SQL(conditions) as SqlOrUndefined<T>;
118120
}
119121

120122
return new SQL([
121123
new StringChunk('('),
122124
sql.join(conditions, new StringChunk(' and ')),
123125
new StringChunk(')'),
124-
]);
126+
]) as SqlOrUndefined<T>;
125127
}
126128

127129
/**
@@ -140,27 +142,26 @@ export function and(
140142
* )
141143
* ```
142144
*/
143-
export function or(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;
144-
export function or(
145-
...unfilteredConditions: (SQLWrapper | undefined)[]
146-
): SQL | undefined {
145+
export function or<T extends (SQLWrapper | undefined)[]>(
146+
...unfilteredConditions: T
147+
): SqlOrUndefined<T> {
147148
const conditions = unfilteredConditions.filter(
148149
(c): c is Exclude<typeof c, undefined> => c !== undefined,
149150
);
150151

151152
if (conditions.length === 0) {
152-
return undefined;
153+
return undefined as SqlOrUndefined<T>;
153154
}
154155

155156
if (conditions.length === 1) {
156-
return new SQL(conditions);
157+
return new SQL(conditions) as SqlOrUndefined<T>;
157158
}
158159

159160
return new SQL([
160161
new StringChunk('('),
161162
sql.join(conditions, new StringChunk(' or ')),
162163
new StringChunk(')'),
163-
]);
164+
]) as SqlOrUndefined<T>;
164165
}
165166

166167
/**

0 commit comments

Comments
 (0)