Skip to content

Commit

Permalink
Pass down type arguments to behaviors
Browse files Browse the repository at this point in the history
  • Loading branch information
flobernd committed Jun 18, 2024
1 parent ff026d8 commit 71a5a2e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
6 changes: 3 additions & 3 deletions output/typescript/types.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 35 additions & 1 deletion typescript-generator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,21 @@ function buildBehaviorInterface (type: M.Interface): string {
// The main difference with this approaches comes when you are actually using the types. 1 and 2 are good when
// you are reading an object of that type, while 3 is good when you are writing an object of that type.
function serializeAdditionalPropertiesType (type: M.Interface): string {
const dictionaryOf = lookupBehavior(type, 'AdditionalProperties') ?? lookupBehavior(type, 'AdditionalProperty')
let dictionaryOf = lookupBehavior(type, 'AdditionalProperties') ?? lookupBehavior(type, 'AdditionalProperty')
if (dictionaryOf == null) throw new Error(`Unknown implements ${type.name.name}`)

const parent = model.types.find(t => t.name.name === type.inherits?.type.name)
if (parent != null && parent.kind === 'interface' && parent.generics != null && parent.generics.length === type.inherits?.generics?.length) {
const map = new Map<M.TypeName, M.ValueOf>();
for (let i = 0; i < parent.generics.length; i++) {
map.set(parent.generics[i], type.inherits.generics[i])
}
dictionaryOf = {
type: dictionaryOf.type,
generics: dictionaryOf.generics?.map(x => replaceGenerics(x, map))
}
}

const extendedPropertyTypes = getAllExtendedPropertyTypes(type.inherits)
const openGenerics = type.generics?.map(t => t.name) ?? []
let code = `export interface ${createName(type.name)}Keys${buildGenerics(type.generics)}${buildInherits(type)} {\n`
Expand Down Expand Up @@ -325,6 +338,27 @@ function serializeAdditionalPropertiesType (type: M.Interface): string {
}
}

function replaceGenerics(value: M.ValueOf, map: Map<M.TypeName, M.ValueOf>): M.ValueOf {
if (value.kind !== 'instance_of') {
return value
}

if (value.generics == null || value.generics.length === 0) {
for (const entry of map) {
if (entry[0].namespace === value.type.namespace && entry[0].name === value.type.name) {
return entry[1]
}
}
return value
}

return {
kind: 'instance_of',
type: value.type,
generics: value.generics.map(x => replaceGenerics(x, map))
}
}

function lookupBehavior (type: M.Interface, name: string): M.Inherits | null {
if (!type.attachedBehaviors?.includes(name)) return null // eslint-disable-line
if (Array.isArray(type.behaviors)) {
Expand Down

0 comments on commit 71a5a2e

Please sign in to comment.