0

I have array of objects. Each object inside array represents an html input field. I want to load different interface on the base of type property inside the field.

interface Field {
  type: 'text' | 'radio';
  name: string;
}
interface TextField {
  placeholder: string;
}
interface RadioField {
  values: {
    value: string;
    label: string;
  }[];
}
const fields: Field[] = [
  {
    // How to make use of TextField interface here
    type: 'text',
    name: 'firstName',
  }
]

1 Answer 1

2

I will recommand you to define the Field type by the union with TextField and RadioField that extends a FieldCommon interface. Like that you are more precise so that a radio field should have values for example:

type Field = TextField | RadioField

interface FieldCommon {
  name: string;
}

interface TextField extends FieldCommon {
  type: 'text'
  placeholder: string;
}

interface RadioField extends FieldCommon {
  type: 'radio'
  values: {
    value: string;
    label: string;
  }[];
}

const fields: Field[] = [
  {
    type: 'text',
    name: 'firstName',
    placeholder:'Test' // valid
  },
  {
    type: 'text',
    name: 'firstName', // error: Property 'placeholder' is missing
  }
]

Playground Link

Sign up to request clarification or add additional context in comments.

1 Comment

@ZeeshanAhmad No problem :/ don't forget to validate the answer if it's answering the question ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.