Type | Treat 2021 - Day 4
Tags: typescript, challenge
Published: 2021-10-28 19:20:37

---
title: Type | Treat 2021 - Day 4
published: true
description: The TypeScript Team challenges
tags: typescript,challenge
series: type | treat 2021
cover_image: https://devblogs.microsoft.com/typescript/wp-content/uploads/sites/11/2021/10/type-or-treat-2021.png
---

## Type | Treat Challenge 4

Welcome to the fourth `Type | Treat` challenge! These challenges are a series of blog posts which have 2 code challenges in, one for beginners and one for intermediate TypeScript programmers. We're on day four, which means going over the answers from [yesterday](https://devblogs.microsoft.com/typescript/type-treat-2021-day-3/) and have 2 new challenges.

## Yesterday's Solution

### Beginner/Learner Challenge

I wonder if we over-indexed on the difficulty here, and we're interested if you dropped off somewhere through this task because we had less submissions than usual for this challenge. The goal was to have you build out a [template string literal](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html) type which accounted for string input which _roughly_ matched how CSS's stringy variables worked.

You started with:

```ts 
type Length = string
```

Which accepts all possible strings, next we show some examples which should always fail. The key one here being that an empty string should fail: `""`. Next we provided some valid input for you to work with:

```ts
type Length = `${number}in`

// Works with:
req("0in")
req("12in")
```

Giving you a sense that a number can be used in the template slot - which allows for all sorts of possibilities. 

Next we gave samples with different prefixes, so `"in"` and `"cm"` would need to be handled. To get that right, you would need to use a union:

```ts
type Unit = "cm" | "in"
type Length = `${number}${Unit}`

// Works with:
req("0in")
req("12in")
req("1.5cm")
req("20cm")
```

Next we threw a curve ball - `"0"` should also be acceptable, this is a bit of a curve ball, but also it's a bit of a trick:

```ts
type Unit = "cm" | "in" | ""
type Length = `${number}${Unit}`

// Works with:
req("0in")
req("12in")
req("1.5cm")
req("20cm")
req("0")
```

The lack of a unit is just an empty string unit! Only one more thing now, and that is allowing a space inbetween the number and unit. This could be done via another type also:

```ts
type Unit = "cm" | "in" | ""
type Space = " " | ""
type Length = `${number}${Space}${Unit}`

// Works with:
req("0in")
req("12in")
req("1.5cm")
req("20cm")
req("0")
req("12 cm")
req("14 in")
```

That was is for the easy parts of the challenge. It's pretty tricky, because it requires that you understand that `number` can be anything in the template string and to understand how a union can allow for different types of strings inside the type. That's all in the main docs, but it could be a lot of ideas to learn at once.

This challenge also had a set of complications, cases where the version of the the `Length` type we expected people to build would provide interesting edge cases:

```ts
req(`${0.3e21}cm`)
req("-12 cm")
req(`${Infinity}cm`)
req(`${NaN}cm`)
```

<details><summary><b>Click to learn about these cases</b></summary>

```ts
req(`${0.3e21}cm`)
```

Acted as a potential clue to an alternative answer for these failing cases:

```ts
req(`${Infinity}cm`)
req(`${NaN}cm`)
```

Because `number` can be switched out with `bigint` in the type of `Length`:

```diff
- type Length = `${number}${Space}${Unit}`
+ type Length = `${bigint}${Space}${Unit}`
```

This meant you couldn't pass in `Infinity` or `NaN` but also broke `req("1.5cm")` because you can't have point values. This could be fixed via: 

```ts
type Length = `${bigint}${Space}${Unit}` | `${bigint}.${bigint}${Space}${Unit}`
```

Which describes both possible cases with a "." and without. This technique still doesn't handle the `req("-12 cm")`, and actually, it introduces a whole new problem: `req("-12.-12cm")` is allowed!

We spotted a good answer from [@danvdk](https://twitter.com/danvdk/status/1453503071087169536) which revolved around using string manipulation instead, by introducing a `Digit` type:

```ts
type Whitespace = '' | ' ';
type Unit = 'in' | 'cm';
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type Length = `${Digit}${number | ''}${Whitespace}${Unit}` | '0';
```

This solution correctly handles the case of `req("-12 cm")` but via that `number` would allow something like `req("1-22 cm")` - which you can pretend is to handle an input range.  It wouldn't be hard to take this solution and reasonably cover additional edge cases. Very cool solution.

</details>

[Our answer](https://www.typescriptlang.org/play?#code/PTAEE0HsFcHICcCmoDul4GsCWA7A5qJDqAJ4zyjQBGi8AtAGbp0AukWANoi3QA4CGvWrjx1+dABYwAzsmkt+8FtF4AoEKH44AJqCGReXUBkSJeoPFgBuI0jFA4isnLNBd8LCdNBMKUlKAAttAAxhKgbJzc6mACQhSeiCSaSBbs+BGQDqbaAHQQ9rhYLFj8HBzJePxWyImguLzQ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OBtVkPyJYkgSyBwNTSLki0Ox6+DSKDYQAMKXIYWAhKGTOIAAst8-yQ1pMMaDL3iy5zBOXecAkfRQjoZAMlg2w47TfJmOCjMUrMp9aO6gAAVnCzQjhoJM4CmhdZrLM05gOJfaM85TJHRIcsCcOfpzKifEHUABSjLwfmopivpuQAMyIBZZmysSKxwfXYDh923jvaPoAXDgsAufw8zOK40XkDFvU0bfxB0QK0hRu53zb-UHQ4BUmghKyvDpV4JAaQxRrBvUErQaQKI8owToPDKqNxawaDqtsPQwCQFsVqObACrhOa0HgHxK6TFEiuCepAKmnNIwf2kngV+hAJj+CRKAWyyAMCOACG8Mh9QlLHhti3FwowvIbkUoYT6RCJAf05rgf4g4SgZBSvwbudBOgMFGCtYS7Q9yoBvOEJUIQoyhh-iHYgA8TgkMQB-EOsgrzFHvG1ZmEQARKJUe7GBc8VLSRxGidegRN4zzzHPdsrYfF+JqjcIAA)

### Intermediate/Advanced Challenge 


The intermediate challenge was on type literals mixed with generics functions. The challenge started with this function:

```ts
function makeTitle(str: string) {
    return "<spooky>" + str.toUpperCase() + "</spooky>"
}
```

The goal was to keep track of string literals through this function. To do this, you need to switch the `str: string` to be a type argument:

```ts
function makeTitle<Str>(str: Str) {
    return "<spooky>" + str.toUpperCase() + "</spooky>"
}
```

You know that the type argument has to be a string, which you can tell TypeScript via `<Str extends string>`, then you can re-use the `Str` in the return position:

```ts
function makeTitle<Str extends string>(str: Str): `<spooky>${Uppercase<Str>}</spooky>` {
    return "<spooky>" + str.toUpperCase() + "</spooky>"
}
```

You'd think this would be it, but `str.toUpperCase` actually converts the `str` to a string! Tricky, you'd need to think creatively here and you have three options:

1. Use an `as` because you know better than the compiler: 

    ```ts
    function makeTitle<Str extends string>(str: Str): `<spooky>${Uppercase<Str>}</spooky>` {
        const shouty = str.toUpperCase() as Uppercase<Str>
        return `<spooky>${shouty}</spooky>`
    }
    ```

2. Override `toUpperCase` to support template literals: 

    ```ts
    interface String {
        toUpperCase<T extends string>(this: T) : Uppercase<T>
    }
    ```

3. Or create a new function which supports template literals.

This would take the `"party"` used on line 19 and convert it to `"<spooky>PARTY</spooky>"`. That change would remove the compiler error on `addTadaEmoji`.

The second part was about re-using the type parameters inside argument for the function. The challenge started with:

```ts
function setupFooter(str: string) {
    // validate string etc
    return { 
        name: str.split(",")[0],
        date: str.split(",")[1],
        address: str.split(",")[2]
    }
}
```

Would lose string literals passed in as `str`. You knew ahead of time that there were three separate parts of information you were interested in:

```ts
function setupFooter<Name extends string, Date extends string, Address extends string>(str: string) {
```

These could then be used inside the replacement for `string`:

```ts
function setupFooter<Name extends string, Date extends string, Address extends string>(str: `${Name},${Date},${Address}`) {
```

Which would correctly set up these variables for re-use later:

```ts
function setupFooter<Name extends string, Date extends string, Address extends string>(str: `${Name},${Date},${Address}`) {
    // validate string etc
    return { 
        name: str.split(",")[0] as Name,
        date: str.split(",")[1] as Date,
        address: str.split(",")[2] as Address
    }
}
```

Successfully completing this challenge would show that `name`, `date` and `address` were not `string` but the strings passed in.

[Our answer](https://www.typescriptlang.org/play?#code/PTAEE0HsFcHIDcCmoDOiAupoAdQENQAbAS3XUOW0hXUQCdQBbPAa2IDsBzUAI2hQ6IUKADT52AE1AAzSAwAWeQoUgB3RInYAoEKACeMWHWQTIHbimyIAxsSUpQq+ZtBXI2CqEVIvSlepdsPDp0YiEAOlAAFWdeIXQdMGlEPHRoY1BiB3RFTANoJlZkHOLSCgdEAA90OgJLSEgWPQBCLUSIGFB2SFDrRCkc1NBrSAlkJ2JreX1OnJhOeUxVGEIpZboWTIdarPNxdvo6ORkjxmi9KwBlazpibExTVXZ8TBLQAAM8CQkor7wAUUYkAAVsR3pEAJKYNCIRjZXIfZgsRBRMqId7tLLsWCYZGIbB7N7oC7ILJEBoCLigN40W5Uki0WqERzOZ6kYaQRhCTLPAC0oHa1jwz3yhWRmUwQWEvD0w0UXEJsTG0g4pGIkGekGkiKKqPI6IA-G1pNB2NZQhqxSi0QAeS41UBVWiSBy08wAPgAFLSAFyge10ACUfveNvqjT07oAJABvACq2CsdCFaDtNXdAF8bcBw013e9QDGtKASxz2DRUPIYMTQABeVA1cLoSAJpMAYTwaE9gfwDlb9BTiDTdHdxdLxjSdGeodzkdjKCr0GJWZzVAj+a0GbaI3LmGMAEdoMRjChfhIAUDQXXQN6an63Vwe7X3YXQBP0s9aXXa-WAERhtc8wABQAQQAJSicBs1nd1fy3HcKy+H4-kBEFiGvW86D9f8YNAiCoNXBo81-J8X3eH10D+H15xqDMfSCEI9B9DEEMwJCokgIDqEZDDfQbOlOFI18ty0VjUAwHAAAkUjGBh627OsXyLUsywrUJ9WvJFrX1T1fwY4kSLaFTiG1T0DyPE8zwvNDPXUihAx7QsxxUkt2JQy9iFstFA2c0ARJU9jOO4+gvP1HyRN0AAZDBYAcHhkCrdh4jEHIyRQPQaFhGY4B8NBMBwLZ8CIUgNOBYUmnaeKhX4UlMEUbJIB5Rk8HNRxSGmAhmCmQQiBSKc9mwI5OFqRhIhiRB2kGyBhrwM5OGIJAHFFHgWs2AgRkYZheTQBjUn6fi9lkBg3lkHp6ExdgjuYC12EiKACh3JAQmpeQyQ4ZsitOni+EwFVJGyug0EIaR2hUSluGJKweSu1J1WeJwXFFGqXrJE0zRuv1jVNc04fEtJsAAMQaRkbQAOVm5AnU0CRXRqcwxAAET2x1qmp2mBLEEDvhPCpWZdA6uC9Pj3ljcmuQzERYyZ2gJdjLmJB5jN3h7ZTS10eAlGIc9aAF7gMGsXz3ynV9fJU9gKfvRtLAZXSRBIgBtAAGABdXtQDFxARFN0ttcQS26HCa3SFth2AEZXc7UBpc973XO5oQUH9wOPGD387cDe2ACYI4ceWed8rcIrACExj8WUUEawY8k6TgMBe5BbgWV4STixB-G3DUKy++hrzynAibOuhdKZrge4AWWsS55U9yS-DUDRnkzx3M9DkRxtACF2EZJL0EM7uA-Nrl2hcgA9I19-CX3j5Us+tAvpD890U+jS0IA).


## The Challenge

### Beginner/Learner Challenge

[Make some candy bowls. Then make some very specific bowls](https://www.typescriptlang.org/play?#gist/927ccc66ae3022dc64c4f650109b937a-13).


### Intermediate/Advanced Challenge  

[Run a set of pumpkin competitions](https://www.typescriptlang.org/play?#gist/927ccc66ae3022dc64c4f650109b937a-14)

## How To Share Your Solution

Once you feel you have completed the challenge, you will need to select the **Share** button in the playground. This will automatically copy a playground URL to your clipboard.

Then either:

 - Go to Twitter, and create a tweet about the challenge, add the link to your code and mention the [@TypeScript](https://twitter.com/typescript) Twitter account with the hashtag [#TypeOrTreat](https://twitter.com/search?q=%23TypeOrTreat).

 - Leave us a comment with your feedback on here!

### Best Resources for Additional Help

If you need additional help you can utilize the following:

- [The New TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
- The [TypeScript Community Discord](https://discord.com/invite/typescript)
- The comments on each [Dev.to](https://dev.to/typescript) post!
- Our previous [`Type | Treat` 2020 challenges](https://www.typescriptlang.org/play/#gist/303ebff59a6fc37f88c86e86dbdeb0e8-0)


Happy Typing :)