Reputation: 3641
I'm writing a function like this:
static checkString(p, opts = {
canBeEmpty: false,
canBeUndefined: false,
maxLength: undefined
}): boolean {
if (opts.canBeUndefined && typeof p === 'undefined') return true;
if (typeof p !== 'string') return false;
if (!opts.canBeEmpty && p.length === 0) return false;
if (typeof opts.maxLength !== 'undefined' && p.length > opts.maxLength) return false;
return true;
}
The parameter opts
has default value. When I want to use it like this:
ParamChecker.checkString(nick, {canBeUndefined: true})
The compiler throws error:
Argument of type '{ canBeUndefined: true; }' is not assignable to parameter of type '{ canBeEmpty: boolean; canBeUndefined: boolean; maxLength: any; }'. Type '{ canBeUndefined: true; }' is missing the following properties from type '{ canBeEmpty: boolean; canBeUndefined: boolean; maxLength: any; }': canBeEmpty, maxLength [2345]
How to make it possible, to call a function with not all properties of a parameter which has default value?
Upvotes: 0
Views: 134
Reputation:
You're providing a default value for the whole of opts
.
So if you provide your own opts
arg then none of the defaults get used.
opts = { canBeEmpty: false, canBeUndefined: false, maxLength: undefined }
i.e. If you don't pass opts, then the default object is used. If you do pass opts then the whole opts object is replaced by the one you pass.
Instead define the Options interface with the properties as optional. Then, inside the function merge the default props with the passed props.
interface Options {
canBeEmpty?: boolean;
canBeUndefined?: boolean;
maxLength?: number;
}
const defaultOptions: Options = {
canBeEmpty: false,
canBeUndefined: false,
maxLength: undefined
};
const checkString = (p, options: Options): boolean => {
const mergedOptions = {
...defaultOptions,
...options
};
if (mergedOptions.canBeUndefined && typeof p === 'undefined') return true;
if (typeof p !== 'string') return false;
if (!mergedOptions.canBeEmpty && p.length === 0) return false;
if (typeof mergedOptions.maxLength !== 'undefined' && p.length > mergedOptions.maxLength) return false;
return true;
}
checkString("", { canBeUndefined: true })
Upvotes: 2