#Satisfies union resolution

11 messages · Page 1 of 1 (latest)

knotty sandal
#

Hey, I'm working in my project and I've noticed some odd behaviour of typescript.
It seems that if one object doesn't contain one property it will just skip it while if both of object's will have 1 different property it will create an union.
Is there any meaning full idea why does this happened?

hasty needleBOT
#
matew9682#0

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) {
...```

indigo oasis
#

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

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.

harsh robin
#

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.

knotty sandal
#

Thats interesting, is this mechanism documented somewhere? I would love to understand what are benefits for such behaviour

harsh robin