2

What should I do in the function createField in order to remove this syntax error highlighting?

const createField = (
    dataType,
    options = {
        required: false,
        label: null,
        min: Number.NEGATIVE_INFINITY,
        max: Number.POSITIVE_INFINITY,
        email: false,
        match: false
    }
) => {
    return {
        dataType,
        options: {
            ...options,
            label: options.label && options.label.toString() || null,
        },
    };
};

enter image description here

1
  • 2
    const inferToPartial = <T>(o: T) => o as Partial<T>; /*...*/ options = inferToPartial({ required: false, /*...*/ }) /*...*/;, alternatively you can type out the entire type again, or pull the default into a variable before the function, and use its type to not have to write it again. Also see e.g. this question's answer Commented Jun 3, 2021 at 10:32

1 Answer 1

1

Here a possible solution:

interface CreateFieldOptions {
  required?: boolean;
  // you need to change the type here
  label?: unknown;
  min?: number;
  max?: number;
  email?: boolean;
  match?: boolean;
}
const createFieldDefaultOptions: CreateFieldOptions = {
  required: false,
  label: null,
  min: Number.NEGATIVE_INFINITY,
  max: Number.POSITIVE_INFINITY,
  email: false,
  match: false
}

const createField = (
    dataType,
    options: CreateFieldOptions = {}
) => {
    return {
        dataType,
        options: {
            ...createFieldDefaultOptions,
            ...options,
            label: options.label && options.label.toString() || null,
        },
    };
};

What are the changes?

  • Add an interface to manage the options type -> CreateFieldOptions
    • So it can be reused
  • Extract the default options into a separate variable -> createFieldDefaultOptions
    • Your intent seems to be to merge the default options with the provided passed options. But that is not possible via the parameter assignment, so it has to be done later (see last bullet point)
  • The type of the options parameter is now an optional CreateFieldOptions
  • The returned object with the options attribute is extended by the createFieldDefaultOptions
    • The order is important! createFieldDefaultOptions needs to be first, so that it can be overridden by the provided options
Sign up to request clarification or add additional context in comments.

Comments

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.