@@ -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' || ! 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