#Generate literal type with required and optional properties

7 messages · Page 1 of 1 (latest)

spare raftBOT
#

@robust oak Here's a shortened URL of your playground link! You can remove the full link from your message.

Orbviox#1805

Preview:```ts
type X<T> = {
[P in keyof T]: T[P] extends {required: true}
? any
: undefined
}

type T = {
hello: {required: true; default: 123}
there: {required: false; default: true}
}

type T2 = X<T>

const test: T2 = {
hello: 12,
}```

#
Gerrit0#7591

Preview:```ts
type Widen<T> = T extends number
? number
: T extends boolean
? boolean
: T extends string
? string
: T

type X<T extends Record<string, {default: unknown}>> =
{
[P in keyof T as T[P] extends {required: true}
? P
: never]: Widen<T[P]["default"]>
} & {
...```

quiet charm
#

!ts T2

spare raftBOT
#
type T2 = {
    hello: number;
} & {
    there?: boolean | undefined;
} /* 17:6, 19:13 */```
quiet charm
#

optionality is different from the type including undefined, so if you need both required and optional properties, you need to intersect two mapped types

robust oak