I am having trouble using initial parameters (I am not sure if there is a typescript solution or it is just a JavaScript question, so I present you the Javascript equivalent to you):
const helloWorldWithOptions = (options = { a:1, b:2 } ) => {
console.log("Hello World!")
};
When using the function:
helloWorldWithOptions( {a:4} );
Typescript says that I am missing the object key b when using the function. What I would expect is that js/ts filling up the missing values with the initial parameters. If there is already a state of the art, let me know.
CodePudding user response:
You can use the Partial type and ... spreading to combine your defaults with the caller's overrides.
const defaults = { a: 1, b: 2 };
// Could use a named type instead of `typeof defaults` too.
const helloWorldWithOptions = (options: Partial<typeof defaults> = {}) => {
const mergedOptions = { ...defaults, ...options };
console.log(mergedOptions);
};
helloWorldWithOptions({ a: 3 });
CodePudding user response:
You can specify default values whenever you declare a function:
function aFunction({a = 1, b = 2}) {console.log(a, b)}
aFunction({}) //prints "1 2"
in this case, 'aFunction' receives an object, and whenever you call the function with an empty object, it automatically fills the blank fields. Alternatively, you can call 'aFunction' with the parameters you want, for example:
aFunction({a: 2, b: 3}) //prints "2 3"
