Skip to content

Commit

Permalink
support number | string union on mapped type
Browse files Browse the repository at this point in the history
  • Loading branch information
sinclairzx81 committed Jul 31, 2023
1 parent 3b30273 commit cd23d3a
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/typescript/typescript-to-typebox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,9 +546,11 @@ export namespace TypeScriptToTypeBox {
set.add('TemplateLiteralParser')
set.add('TemplateLiteralGenerator')
set.add('TTemplateLiteral')
set.add('TPropertyKey')
set.add('TypeGuard')
set.add('TSchema')
set.add('TRecord')
set.add('TString')
set.add('TNumber')
set.add('TUnion')
set.add('TLiteral')
}
Expand All @@ -558,17 +560,22 @@ export namespace TypeScriptToTypeBox {
function MappedSupport() {
return useMapped
? [
'type MappedConstraint = TTemplateLiteral | TUnion<TLiteral<string>[]> | TLiteral<string>',
'type MappedContraintKey = TNumber | TString | TLiteral<TPropertyKey>',
'type MappedConstraint = TTemplateLiteral | TUnion<MappedContraintKey[]> | MappedContraintKey',
'type MappedFunction<C extends MappedConstraint, S extends TSchema = TSchema> = (C: C) => S',
'function Mapped<C extends MappedConstraint, F extends MappedFunction<C>>(C: C, F: F): TRecord<C, ReturnType<F>> {',
'// prettier-ignore',
'function Mapped<C extends MappedConstraint, F extends MappedFunction<C>>(C: C, F: F) {',
' return (',
' TypeGuard.TTemplateLiteral(C) ? (() => {',
' const E = TemplateLiteralParser.ParseExact(C.pattern)',
' const K = TemplateLiteralFinite.Check(E) ? [...TemplateLiteralGenerator.Generate(E)] : []',
' return Type.Object(K.reduce((A, K) => ({ ...A, [K]: F(Type.Literal(K) as any)}), {}))',
' })() :',
' TypeGuard.TUnion(C) ? Type.Object(C.anyOf.reduce((A, K) => ({ ...A, [K.const]: F(K as any)}), {}))',
' : Type.Object({ [C.const]: F(C) })) as any',
' TypeGuard.TUnion(C) ? Type.Object(C.anyOf.reduce((A, K) => ({ ...A, [K.const]: F(K as any)}), {})) : ',
' TypeGuard.TString(C) ? Type.Record(C, F(C)) : ',
' TypeGuard.TNumber(C) ? Type.Record(C, F(C)) : ',
' Type.Object({ [C.const]: F(C) })',
' )',
'}',
].join('\n')
: ''
Expand Down

0 comments on commit cd23d3a

Please sign in to comment.