hapijs / hapijs/joi

Support intersecting union types (concat an object with alternatives)

Open
#3,057 0 comments 0 reactions 0 assignees View on GitHub
feature
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

### Runtime

node.js

### Runtime version

22

### Module version

17.13.3

### Used with

@nahkies/openapi-code-generator

### Any other relevant information

_No response_

### What problem are you trying to solve?

Related: https://github.com/mnahkies/openapi-code-generator/issues/282

In openapi 3 definitions you can intersect schemas with unioned schemas, essentially forming something like this in typescript terms:
```typescript
(A | B) & C
```

At the moment the generator attempts to define this as something like:
```typescript
const x = joi
.alternatives()
.try(
joi
.object()
.keys({foo: joi.string().required()})
.options({stripUnknown: true})
.required(),
joi
.object()
.keys({bar: joi.string().required()})
.options({stripUnknown: true})
.required(),
)
.required()
.concat(
joi
.object()
.keys({id: joi.string().required()})
.options({stripUnknown: true})
.required(),
)
.required()
```

However this results in a runtime error like:
```
[Error: Cannot merge type alternatives with another type: object]
```
([unit test here](https://github.com/mnahkies/openapi-code-generator/pull/283/files#diff-2f29bdaaa698963024b3236513ef655df323570dd1fcc0f1476c915b8e5c69ccR1188-R1248))

### Do you have a new or modified API suggestion to solve the problem?

I'll skip that test for now, and leave it as a known issue, but it would be great if it would be possible to `concat` into `alternatives`.

**Alternatives**
I suspect I could probably come up with a way to detect definitions of this nature, and basically re-write / invert them such that it was a union of intersections, instead of an intersected union. Eg:
```typescript
(A & C) | (A & C)
```
But I think this would probably be quite complicated to do correctly supporting arbitrary input.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.