#Satisfies union resolution
11 messages · Page 1 of 1 (latest)
Preview:```ts
interface ExampleType {
a?: string;
b: string;
c: string;
d?: string;
}
const example1Data = {
option1: {
b: "test",
c: "test2",
d: "test3"
},
option2: {
a: "test",
b: "test2",
c: "test3"
}
} satisfies Record<string, ExampleType>
function getExample1Item(key: keyof typeof example1Data) {
...```
For inferred return values TS tries to infer a common supertype
Since this reduction can't be done for the return value of the first function it is left as is
For the second one it sees that { a, b, c } is a subtype of { b, c } and only leaves the latter
@knotty sandal
Do you know if that is actually expected behaviour?
When it will drop this property I have to do some hacks to actually get access to this a field.
Yeah, this is expected.
You can add an explicit type annotation with the union type if you want the function to return a union instead of the base type.
Thats interesting, is this mechanism documented somewhere? I would love to understand what are benefits for such behaviour
Not sure if this is explicitly called out in the handbook or not. But this is a pretty useful behavior in a lot of cases where inferring a union would create a type that's a lot more specific/fragile than intended.