If you want to provide multiple signatures for a function, you can utilize function overloading:
function myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: true, values: Array<any>): void
function myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: false): void
function myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: boolean, values?: Array<any>): void {
if (onlyValues) {
// When running the function, `values` should be provided but it's not always guaranteed
// Check for its existence and handle cases where it may be missing
console.log(values);
}
console.log(allData);
console.log(selectedItems);
console.log(onlyValues);
}
myFunction([1, 2, 3], [1, 3], true); // error, when `values` is not included, `onlyValues` should be false
myFunction([1, 2, 3], [1, 3], true, ['a', 'b']); // OK, `onlyValues` === true, `value` is provided
myFunction([1, 2, 3], [1, 3], false); // OK, `onlyValues` === false, `value` is not required
myFunction([1, 2, 3], [1, 3], false, ['a', 'b']); // error, `onlyValues` === false, `value` should not be included
Visit the TypeScript playground for more information.