Skip to content

Commit 8b65b39

Browse files
authored
fix(typescript): union unknown null (#995)
* fix(typescript): unknown is already nullable Fixes: supabase/cli#4234 supabase/cli#577 * fix: also exclude any from null union
1 parent 12217b2 commit 8b65b39

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

src/server/templates/typescript.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,14 @@ export const apply = async ({
482482
}`
483483
: ''
484484

485+
function generateNullableUnionTsType(tsType: string, isNullable: boolean) {
486+
// Only add the null union if the type is not unknown as unknown already includes null
487+
if (tsType === 'unknown' || tsType === 'any' || !isNullable) {
488+
return tsType
489+
}
490+
return `${tsType} | null`
491+
}
492+
485493
function generateColumnTsDefinition(
486494
schema: PostgresSchema,
487495
column: {
@@ -497,7 +505,7 @@ export const apply = async ({
497505
views: PostgresView[]
498506
}
499507
) {
500-
return `${JSON.stringify(column.name)}${column.is_optional ? '?' : ''}: ${pgTypeToTsType(schema, column.format, context)} ${column.is_nullable ? '| null' : ''}`
508+
return `${JSON.stringify(column.name)}${column.is_optional ? '?' : ''}: ${generateNullableUnionTsType(pgTypeToTsType(schema, column.format, context), column.is_nullable)}`
501509
}
502510

503511
let output = `
@@ -537,7 +545,7 @@ export type Database = {
537545
...schemaFunctions
538546
.filter(({ fn }) => fn.argument_types === table.name)
539547
.map(({ fn }) => {
540-
return `${JSON.stringify(fn.name)}: ${getFunctionReturnType(schema, fn)} | null`
548+
return `${JSON.stringify(fn.name)}: ${generateNullableUnionTsType(getFunctionReturnType(schema, fn), true)}`
541549
}),
542550
]}
543551
}
@@ -610,7 +618,7 @@ export type Database = {
610618
.filter(({ fn }) => fn.argument_types === view.name)
611619
.map(
612620
({ fn }) =>
613-
`${JSON.stringify(fn.name)}: ${getFunctionReturnType(schema, fn)} | null`
621+
`${JSON.stringify(fn.name)}: ${generateNullableUnionTsType(getFunctionReturnType(schema, fn), true)}`
614622
),
615623
]}
616624
}
@@ -709,12 +717,15 @@ export type Database = {
709717
const type = typesById.get(type_id)
710718
let tsType = 'unknown'
711719
if (type) {
712-
tsType = `${pgTypeToTsType(schema, type.name, {
713-
types,
714-
schemas,
715-
tables,
716-
views,
717-
})} | null`
720+
tsType = `${generateNullableUnionTsType(
721+
pgTypeToTsType(schema, type.name, {
722+
types,
723+
schemas,
724+
tables,
725+
views,
726+
}),
727+
true
728+
)}`
718729
}
719730
return `${JSON.stringify(name)}: ${tsType}`
720731
})}

0 commit comments

Comments
 (0)