function buildValue()

in typescript-generator/src/index.ts [85:138]


function buildValue (type: M.ValueOf, openGenerics?: string[], origin?: M.TypeName): string | number | boolean {
  function equalTypeNames (t1: M.TypeName, t2?: M.TypeName): boolean {
    return t2 != null && (t1.name === t2.name && t1.namespace === t2.namespace)
  }

  function getShortcutType (value: M.ValueOf): M.ValueOf | undefined {
    if (value.kind === 'instance_of') {
      const def = model.types.find(t => equalTypeNames(t.name, value.type))
      if (def?.kind === 'interface' && def.shortcutProperty != null) {
        const shortcutProp = def.properties.find(p => p.name === def.shortcutProperty)
        return shortcutProp?.type
      }
    }
  }

  switch (type.kind) {
    case 'instance_of':
      if (Array.isArray(openGenerics) && openGenerics.includes(type.type.name)) {
        return type.type.name
      }

      if (!equalTypeNames(type.type, origin)) {
        // If this type has a shortcut property, generate it as a union of [type, property's type]
        const shortcutType = getShortcutType(type)
        if (shortcutType != null) {
          const union: M.UnionOf = {
            kind: 'union_of',
            items: [type, shortcutType]
          }
          return buildValue(union, openGenerics, type.type)
        }
      }

      if (type.type.name === 'binary' && type.type.namespace === '_builtins') {
        return 'ArrayBuffer'
      }

      return `${createName(type.type)}${buildGenerics(type.generics, openGenerics)}`
    case 'array_of':
      return type.value.kind === 'union_of' || getShortcutType(type.value) != null
        ? `(${buildValue(type.value, openGenerics)})[]`
        : `${buildValue(type.value, openGenerics)}[]`
    case 'union_of':
      return type.items.map(t => buildValue(t, openGenerics, origin)).join(' | ')
    case 'dictionary_of': {
      const result = `Record<${buildValue(type.key, openGenerics)}, ${buildValue(type.value, openGenerics)}>`
      return type.singleKey ? `Partial<${result}>` : result
    }
    case 'user_defined_value':
      return 'any'
    case 'literal_value':
      return typeof type.value === 'string' ? `'${type.value}'` : type.value
  }
}