#Getting type of optional field from union

3 messages · Page 1 of 1 (latest)

last musk
#

How to get type of property that's not defined for every union member?

type TypeA = { a: string }
type TypeB = { a: number; b: number }
type TypeC = { c: number }
type UnionType = TypeA | TypeB | TypeC

For example, property "a" in this sample union is of type string | number | undefined. How to get this type (during compile time, without run-time JS code)?

The closest I could get so far is this:

type PropertyA = (UnionType & { a: {} })['a'] // This gives me string | number | {}

But the type contains an extra {} that I couldn't get rid of.

https://www.typescriptlang.org/play?#code/C4TwDgpgBAKuEEEoF4oG8oEMBcUDOwATgJYB2A5lAL4BQoks8AQiulrqQK4C2ARhIQDcUXhx79C1OvEaQAwqwwBjMXwFT60AKqliAe1JwGqI4igAfWRBaXTcmjQD0jqAAk9AdyjA9UchGBvGT0AMygwQj1IQlBvAAtMYAByPChSPUCAEwgQsghMqBC9SUwAG1KoTl0DKG4INUI8AH4HZzcBCBT46CVSvTwIAigASSSAN2hyDPxfEMxCbGkGAAVI6NAkVAAKHX1DGQAyNhx0KmoASgBtJMwkgF0oNoISCgs08XVLNFonF2A44ipcjECapZ5kSjmAAFXAaFih31+Ik4gWGaQg+XwRAh8NhEigxSxL0hMI+kmhVWyuVI+SAA

dusty lintelBOT
#
nonspicyburrito#0

Preview:```ts
type TypeA = {a: string}
type TypeB = {a: number; b: number}
type TypeC = {c: number}
type UnionType = TypeA | TypeB | TypeC

type ValueOf1<T, K extends PropertyKey> = T extends {
[P in K]: infer V
}
? V
: undefined
type A1 = ValueOf1<UnionType, "a">
...```

last musk
#

!resolved