#RequireField Generic not supporting `T | undefined`

6 messages · Page 1 of 1 (latest)

lean spoke
#

Hi all, I'm trying to make a RequiredField generic that takes a Type T and a true/false param. If True, only Type T should be allowed. If false, then Type T | undefined should be allowed.
However, with the following example, if I omit testField, Typescript errors saying that testField is required.

type RequireField<
  T,
  IsRequired extends boolean = false
> = IsRequired extends true ? T : T | undefined;

export interface Test<IsPopulated extends boolean = false> {
  testField: RequireField<Uint8Array, IsPopulated>;
}

// Typescript complains that testField is required here.
const test: Test<false> = {};

Can anyone see what I'm doing wrong here? I've used a similar pattern to allow other types (e.g. T | string) and that seems to work okay.

strong remnant
#

Test<false> evaluates to a type like this:

type Blah = {
  testField: Uint8Array | undefined
}

which is different from a type with an optional property:

type Blah = {
  testField?: Uint8Array | undefined
}
#

you need to work one layer up if you want to make the property conditionally optional

#

for example:

sacred merlinBOT
#
mkantor#0

Preview:```ts
type RequireField<
T,
IsRequired extends boolean = false

= IsRequired extends true
? {testField: T}
: {testField?: T}

export type Test<IsPopulated extends boolean = false> =
RequireField<Uint8Array, IsPopulated>

const test: Test<false> = {}```

strong remnant
#

(not sure if that's the best way to actually structure things. i'd need to know more about your use case)