#How to detect if a parameter / object entry is optional?

25 messages · Page 1 of 1 (latest)

hardy brambleBOT
#
EBKey#2639

Preview:```ts
type MyOptionalFunc = (
props?: number | undefined
) => void
type MyRequiredFunc = (
props: number | undefined
) => void

// Cannot touch above

type IsOptional = unknown // this exists just to help me explain
type IsParamOptional<
T extends MyOptionalFunc | MyRequiredFunc

= Parameters<T>[0] extends IsOptional ? true : false
...```

jolly comet
#

I believe above sample explains what I'm trying to achieve

hardy brambleBOT
#
That_Guy977#5882

Preview:```ts
type MyOptionalFunc = (
props?: number | undefined
) => void
type MyRequiredFunc = (
props: number | undefined
) => void

// Cannot touch above

type IsParamOptional<
T extends MyOptionalFunc | MyRequiredFunc

= Parameters<T> extends Required<Parameters<T>>
? false
: true
...```

dense viper
#

this works for the example you've given but it checks the entire tuple of parameters at once

#

not sure how you could do it for just a single parameter tbh

jolly comet
#

hmm thank you, this should be it

#

i need to check from multiple parameters

#

but this is a good lead

#

ill extract the param, create an object/new func with it alone and check it that way

#

^ okay for objects but not for funcs

valid oracle
#

so you'd need to avoid T[index] and only do T extends [unknown, unknown, unknown, infer Fourth, ...unknown[]] ? IsSingleParamOptional<Fourth> : never

#

or use a recursive type i guess

#

wait no

jolly comet
#

T extends [T, infer X, ...Parameters<T>] something?

valid oracle
#

no, you'll have to make it so that the rest parameter contains just the one element

#

so something like:

[unknown, unknown, unknown, unknown, ...infer End]
[...infer Start, End]
[unknown, unknown, unknown, ...infer Fourth]
#

or maybe you could do something cursed with mapped types

jolly comet
#

i think good inferface would be: IsOptional<T extends Func, Index extends number>

jolly comet
hardy brambleBOT
#
EBKey#2639

Preview:```ts
...
type IsParamOptional<
T extends MyOptionalFunc | MyRequiredFunc,
I extends number

= Pick<Parameters<T>, I> extends Required<
Pick<Parameters<T>, I>

? false
: true
...```

jolly comet
#

thanks @dense viper @valid oracle

#

!resolved

valid oracle
#

🤦