microsoft / microsoft/typespec

[compiler] Allow `@discriminated` union variants to be unions when `envelope` is "none"

Open
#9,817 0 comments 0 reactions 0 assignees View on GitHub
compiler:core design:needed triaged:core
Dominant language
Java
Stars
5.9k
Forks
394
Avg merge
1d 23h
Merged PRs (30d)
104

Description

### Clear and concise description of the problem

Currently, in `@discriminated(#{ envelope: "none"})` unions, we require variants to be _models_ that have the discriminator property on them set to the correct value (`Error: invalid-discriminated-union-variant` if not). I propose that we allow a discriminated union variant to also be a union if each variant of the sub-union conforms to the discriminator property rule. This would allow constructs like the following:

```tsp
@discriminated(#{ envelope: "none", discriminatorPropertyName: "kind" })
union X {
a: A;
b: B;
}

model A {
kind: "a";
//...
}

@discriminated(#{ envelope: "none", discriminatorPropertyName: "bKind" })
union B {
c: C;
d: D;
}

model C {
kind: "b";
bKind: "c";
// ...
}

model D {
kind: "b";
bKind: "d";
// ...
}
```

I ran into this trying to describe a schema with this sort of structure, where one of the variants of a top level union discriminated by "kind" itself has several subvariants discriminated by its own separate property.

### Checklist

- [x] Follow our [Code of Conduct](https://github.com/microsoft/typespec/blob/main/CODE_OF_CONDUCT.md)
- [x] Read the [docs](https://typespec.io/docs/).
- [x] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.

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.