so I am trying to make a object parameter optional, with optional props, and have a default value at the same time:
JavaScript
x
4
1
const myfunc = ({ stop = false }: { stop?: boolean } = { stop: false }) => {
2
// do stuff with "stop"
3
}
4
this works fine, but notice that crazy function definition!
Any way to not repeat so much code?
Advertisement
Answer
I would probably write this like this:
JavaScript
1
15
15
1
interface MyFuncOptions {
2
stop: boolean;
3
}
4
const myFunc = (options: Partial<MyFuncOptions> = {}) => {
5
const defaultOptions: MyFuncOptions = {
6
stop: false,
7
};
8
const finalOptions = {
9
defaultOptions,
10
options
11
}
12
const { stop } = finalOptions;
13
// ...
14
}
15