100% Optional
This is how, using destructuring, you can use the options object pattern in typescript (playground link):
interface Options {
lastSeparator?: string;
separatorBetweenArrayOfTwo?: string;
wrap?: (word: string) => string;
}
const separatedMessage = (
words: string[],
separator: string,
{
lastSeparator = separator,
separatorBetweenArrayOfTwo = lastSeparator,
wrap = (word: string): string => {
return word.toString();
}
}: Options = {} // the `= {}` at the end lets you skip this arguments completely. e.g., `separatedMessage(["a"], " ");` will compile. Without `= {}`, you would have to call it like this to compile: `separatedMessage(["a"], " ", {});`
): string => {
let buf = '';
words.forEach((word, index, array) => {
if (index !== 0) {
if (array.length === 2) {
buf += separatorBetweenArrayOfTwo;
} else if (index === array.length - 1) {
buf += lastSeparator;
} else {
buf += separator;
}
}
buf += wrap(word);
});
return buf;
};
console.log(separatedMessage(["a", "b", "c", "d"], ", "))
console.log(separatedMessage(["a", "b"], ", ", {}))
console.log(separatedMessage(["a", "b"], ", ", {lastSeparator: ", and "}))
console.log(separatedMessage(["a", "b"], ", ", {lastSeparator: ", and ", separatorBetweenArrayOfTwo: " and "}))
This function lets you pass in an array of words and separate them with characters. You can optionally:
- Specify a different separator to use last:
, and in a, b, c, and d.
- Specify a separator that's used for arrays of exactly two elements:
and in a and b but , and in a, b, c, and d.
- Pass in a function that wraps each word in a string:
' in 'a', 'b', 'c', and 'd'
Some required properties
Playground link
type Options = {
r1: string;
o2?: number;
o3?: string;
r4: number;
};
foo('qux', {
r1: 'baz',
r4: 3,
});
function foo(r0: string, { r1, o2 = 6, o3 = 'bar', r4 }: Options) {
console.log(`r0=${r0} r1=${r1} o2=${o2} o3=${o3} r4=${r4}`); // r0=qux r1=baz o2=6 o3=bar r4=3
}
/*
foo('qux', {
r4: 3,
});
Error: Argument of type '{ r4: number; }' is not assignable to parameter of type 'Options'.
Property 'r1' is missing in type '{ r4: number; }' but required in type 'Options'.
*/