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
- 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
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