A
A
Anton2021-11-19 10:59:41
typescript
Anton, 2021-11-19 10:59:41

How to correctly set the union of types (union)?

Hello.
There are the following types:

export type TFormFieldValue = string | number | boolean;
export interface TFormField<T extends TFormFieldValue> {
  value?: T;
  defaultValue?: T;
  emptyValue?: T;
  onChange?: (value: T) => void;
}

export type TFormFieldsUnion =
  | TFormField<string>
  | TFormField<boolean>
  | TFormField<number>


and accordingly the code:

const field1: TFormField<string> = {
...
}

const field2: TFormField<number> = {
...
}

const fields: TFormFieldsUnion = {
    field1,
    field2,
    ...
}


How to correctly set the union of types? (If I'm calling things correctly)
It confuses me that over time TFormFieldsUnion can grow to infinity.
Perhaps there is a more "correct" way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2021-11-19
@karminski

Did you need it? Do not quite understand)

export type TFormFieldsUnion = TFormField<string> | TFormField<boolean> | TFormField<number>


const field1: TFormField<string> = {}

const field2: TFormField<number> = {}

// Array
const fields_a: TFormFieldsUnion[] = [field1, field2]
// Object
const fields_o: { [key: string]: TFormFieldsUnion } = { field1, field2 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question