Typescript - Defaulting Parameters

Typescript - Defaulting Parameters

Referencing function parameter as the default for another parameter.

Background

Recently, I was reviewing some JavaScript challenges and came across one where I was asked to merge two arrays. The twist is that if only one array is passed, then the function should duplicate the second array.

Initial Attempt

"Easy" was my initial reaction.

typescript
1function merge(first: any[], second?: any[]) {
2    if (second) {
3        return [...first, ...second];
4    }
5    else {
6        return [...first, ...first];
7    }
8}

Then I decided to use the nullish coalescing operator to show that I am a TS Pro!

typescript
1function merge(first: any[], second?: any[]) {
2    return [...first, ...(second ?? first)];
3}

Blow My Mind

I reviewed the solution offered by someone else, and my immediate reaction was "Newbie, you can't do that!"

typescript
1function merge(first: number[], second: number[] = first) {
2    return [
3        ...first,
4        ...second
5    ]
6}

Certainly, you can't reference parameter as the default for another parameter! But, it turns out you can! How cool is that!

Challenge

Difficulty: easy

So far, there is nothing specific to Typescript in our examples. We could have done this in JavaScript. (The challenge was for JS after all).

Enter our TS version of the challenge that

Write a function that will create a tuple with three elements from the function's arguments. Here is the TS definition of the function:

typescript
1type Primitive = 'string' | 'number' | 'boolean';
2type Primitive = string | number | boolean;
3type TriTupleBuilder<T extends Primitive> = (a: T, b: T, c: T) => [
4    typeof a,
5    typeof a | typeof b,
6    typeof a | typeof b | typeof c];

Like the example discussed earlier, the function will use the value of the first argument for the second argument if it is missing. Similarly, the function will use the value of the second argument if the third argument is missing.

Here are some test cases:

typescript
1console.log(buildTriTuple(true));           // [true,true,true]
2console.log(buildTriTuple("one", "two"));   // ["one","two","two"]
3console.log(buildTriTuple(1,2,3));          // [1,2,3]
4console.log(buildTriTuple(1,"two",false));  //ERROR

Here is an example solution.

popularity
Re-Emerging
posted
Sep. 18, 2023