Issue
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.
Solution
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 });
Answered By - AKX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.