Connect, collaborate, and grow with a community of TypeScript developers
new(challenge): generic function arguments (#947)
Dimitri Mitropouloscaeaa4f251ec
diff --git a/challenges/challenge-guidelines.md b/challenges/challenge-guidelines.mdnew file mode 100644index 00000000..850de031--- /dev/null+++ b/challenges/challenge-guidelines.md@@ -0,0 +1,205 @@+<!-- omit in toc -->+# TypeHero Challenge Guidelines++- [Writing `prompt.md`](#writing-promptmd)+ - [Keep It Fun](#keep-it-fun)+ - [Encourage Healthy Practices](#encourage-healthy-practices)+- [Writing `test.ts`](#writing-testts)+ - [`Expect<Equal<` Type Order](#expectequal-type-order)+ - [Avoid Type Tuples](#avoid-type-tuples)+ - [Say _Why_ An Error Occurs](#say-why-an-error-occurs)+- [Writing `user.ts`](#writing-userts)+ - [Don't Use `any`, Prefer `unknown`](#dont-use-any-prefer-unknown)+ - [Avoid "Leading The Witness"](#avoid-leading-the-witness)++This is a guide to help you write a challenge for TypeHero. Our goal is to keep the writing process straightforward while at the same time having some consistency. We've learned from experience that there are a few useful things to do to make it a more consistent (and less chaotic) feeling experience for our users. Some of these things are arbitrary design choices. That's ok. It's not about a "right way of doing things" but more "a cohesive experience for users".++In general, if you find yourself having to pick between:++1. more work for yourself when writing the challenge+1. more work for users when taking the challenge++You should prefer more work for yourself at a 10,000:1 ratio.++## Writing `prompt.md`++### Keep It Fun++Try to keep them fun and find widely relatable pop-culture references (without getting political or anything like that). Things like movies, video games, music, art, and anything a large number of people are likely to be familiar with. If you can work in some kind of interesting and lesser-known science fact or something that can also help the reader feel more engaged.++### Encourage Healthy Practices++Avoid using `T` and `U` and `S` as generic parameters names. That doesn't mean there's never a place for them. Just avoid it if you can. For SUPER generic types (like `Pick`), it's fine to use `T`.++## Writing `test.ts`++### `Expect<Equal<` Type Order++Make sure that the thing that's in the `Expect<Equal<` block _first_ is the thing _the user writes_.++<table>+<thead>+<tr>+<th>:white_check_mark: Do :white_check_mark:</th>+<th>:x: Don't :x:</th>+</tr>+</thead>+<tbody>+<tr>+<td>++```ts+type test_TheCoolestCarEverMade = Expect<Equal<+ TheCoolestCarEverMade,+ "Toyota Corolla"+>>;+```++</td>+<td>++```ts+type test_TheCoolestCarEverMade = Expect<Equal<+ "Toyota Corolla",+ TheCoolestCarEverMade+>>;+```++</td>+</tr>+</tbody>+</table>++### Avoid Type Tuples++Don't use constructions like this:++<table>+<thead>+<tr>+<th>:white_check_mark: Do :white_check_mark:</th>+<th>:x: Don't :x:</th>+</tr>+</thead>+<tbody>+<tr>+<td>++```ts+type test_MyThing1 = Expect<Equal<MyThing1, 'thing 1'>>;+type test_MyThing2 = Expect<Equal<MyThing2, 'thing 2'>>;+type test_MyThing3 = Expect<Equal<MyThing3, 'thing 3'>>;+type test_MyThing4 = Expect<Equal<MyThing4, 'thing 4'>>;+```++</td>+<td>++```ts+type tests = [+ Expect<Equal<MyThing1, 'thing 1'>>;+ Expect<Equal<MyThing2, 'thing 2'>>;+ Expect<Equal<MyThing3, 'thing 3'>>;+ Expect<Equal<MyThing4, 'thing 4'>>;+]+```++</td>+</tr>+</tbody>+</table>++Why? Well what if you have a problem where only `MyThing3` is failing, if the test is written with a tuple type it's really difficult to debug the computed result of `MyThing3` that without taking `MyThing3` out and assigning it to an alias. That's a pretty bad experience for users. We can do that work for them upfront.++Time to get comfortable with multicursor editing!++### Say _Why_ An Error Occurs++When you have a test that is intentionally checking for an error, like++```ts+// @ts-expect-error+type test_MyThing_string = MyThing<string>;+```++try to add a little description:++```diff+- // @ts-expect-error++ // @ts-expect-error `MyThing` has a generic constraint that should reject strings+type test_MyThing_string = MyThing<string>;+```++## Writing `user.ts`++### Don't Use `any`, Prefer `unknown`++Unless your challenge is related to `any`, avoid using it. That means you should every helper type equal to `unknown` (not `any`).++<table>+<thead>+<tr>+<th>:white_check_mark: Do :white_check_mark:</th>+<th>:x: Don't :x:</th>+</tr>+</thead>+<tbody>+<tr>+<td>++```ts+type Split = unknown;+```++</td>+<td>++```ts+type Split = any;+```++</td>+</tr>+</tbody>+</table>++### Avoid "Leading The Witness"++One goal of TypeHero is to keep things as real-world as possible (except in the case of challenges that are literally just "for science" like JSON parsers, etc.). That means that you want to give people as much on-the-ground experience as possible. You want users to leave a challenge feeling like they actually learned or accomplished something (or both!).++We want to encourage good behaviors that will carry users into their daily work.++<table>+<thead>+<tr>+<th>:white_check_mark: Do :white_check_mark:</th>+<th>:x: Don't :x:</th>+</tr>+</thead>+<tbody>+<tr>+<td>++```ts+type Split = unknown;+```++</td>+<td>++```ts+type Split<S> = unknown;+```++```ts+type Split<S extends string> = unknown;+```++```ts+type Split<S> = S extends /* your code here */+```++</td>+</tr>+</tbody>+</table>diff --git a/challenges/generic-function-arguments/metadata.json b/challenges/generic-function-arguments/metadata.jsonnew file mode 100644index 00000000..55bb1935--- /dev/null+++ b/challenges/generic-function-arguments/metadata.json@@ -0,0 +1,7 @@+{+ "id": "generic-function-arguments",+ "label": "Generic Function Arguments",+ "description": "Give generic function types to your functions",+ "difficulty": "beginner",+ "prerequisites": ["generic-type-arguments"]+}diff --git a/challenges/generic-function-arguments/prompt.md b/challenges/generic-function-arguments/prompt.mdnew file mode 100644index 00000000..a8163ae5--- /dev/null+++ b/challenges/generic-function-arguments/prompt.md@@ -0,0 +1,80 @@+## Why Functions Need Generics++One of the most common needs a TypeScript developer faces is the need to pass generic type arguments to functions. Then, those functions can use and manipulate those parameters.++In many situations, we don't need functions to be generic. The function might be written in such a way as to only work for one type of data (e.g. `string` or `number`). But, other times, we write functions where we want to pass the data type along from input to output.++## Understanding Generic Syntax++In a previous challenge on [generic type arguments](https://typehero.dev/challenge/generic-type-arguments) we saw a `Row` type that looked like this:++```ts+interface Row<T> {+ label: string;+ value: T;+ disabled: boolean;+}+```++Imagine, though, that you had a function `createRow` that returns an object that looked like our `Row` type:++```ts+const createRow = (+ label: string,++ // how do we provide a type for `value`?+ value: unknown,++ disabled = false,+) => ({+ label,+ value,+ disabled,+});+```++Similarly to how we used the `<` and `>` for our `Row` interface, we place the `<` and `>` right before the parenthesis that start our function's arguments.++```ts+const createRow = <T>(+ label: string,+ value: T,+ disabled = false,+) => ({+ //...+})+```++This is great! Now our `value` parameter has the right type!++### A Word On A Syntax Quirk++You may see the `<T,>` syntax out in the wild. There's an unfortunate niggle with TypeScript's syntax that this is used to work around. Imagine being a parser and seeing `const createRow = <T>`. If you don't know what's coming next it could be ambiguous between these two things++```ts+// Thing 1: Start of JSX+const createRow = <T>Some JSX stuff!</T>;++// Thing 2: start of generic function+const createRow = <T>(someArg: T) => {+ /* some function stuff */+}+```++Because of this ambiguity, we need to do something to _disambiguate_ these two situations to the TypeScript compiler. In the early days it used to be common to use `<T extends unknown>` (or `<T extends any>` in the days before `unknown` existed in TypeScript). But over time people realized there's a shorter way: `<T,>`. Because `,` is invalid in JSX, but valid in TypeScript to separate multiple arguments, it's sufficient to use this to disambiguate the two situations to the TypeScript compiler.++All that to say, if you see this strange syntax know that it's not you, it's TypeScript being a bit funky. If this is confusing to you, just skip it and come back here and read it again when the day comes that you first see this syntax out in the wild.++## Solving This Challenge++This challenge asks you to make an `identity` function. This function does nothing and returns what it was passed with no modifications.++> Note: mathematicians love `identity` operations, so computer scientists use them too so we can seem cool to the mathematicians.++The next function (`mapArray`) is admittedly pretty hard, but take it slow and think about it one step at a time. Ask yourself:++> what is the type of `arr`++Then provide a generic argument as a type for `arr`. After you do that, think about what types you need to provide for `fn`.++In this particular case, if you spend a few minutes with it don't be afraid to check out some solutions. This second example is here more to widen your perspective than anything else. It's good to wrestle with tough problems, even ones that are above your ability level.diff --git a/challenges/generic-function-arguments/solutions/1.ts b/challenges/generic-function-arguments/solutions/1.tsnew file mode 100644index 00000000..e17bf26b--- /dev/null+++ b/challenges/generic-function-arguments/solutions/1.ts@@ -0,0 +1,3 @@+const identity = <T,>(input: T) => input;++const mapArray = <T, U>(arr: T[], fn: (item: T) => U) => arr.map(fn);\ No newline at end of filediff --git a/challenges/generic-function-arguments/tests.ts b/challenges/generic-function-arguments/tests.tsnew file mode 100644index 00000000..d275b76f--- /dev/null+++ b/challenges/generic-function-arguments/tests.ts@@ -0,0 +1,58 @@+import { Expect, Equal } from 'type-testing';++/** temporary */+const expect = <T>(a: T) => ({+ toEqual: (b: T) => a === b+});++const identity_string = identity("this is a string");+expect(identity_string).toEqual("this is a ...");+type test_identity_string = Expect<Equal<+ typeof identity_string,+ string+>>;++const identity_number = identity(123.45);+expect(identity_number).toEqual(123.45);+type test_identity_number = Expect<Equal<+ typeof identity_number,+ number+>>;++const identity_boolean = identity(false);+expect(identity_boolean).toEqual(false);+type test_identity_boolean = Expect<Equal<+ typeof identity_boolean,+ boolean+>>;++const strings = ['1', '1', '2', '3', '5'];+const numbers = [1, 1, 2, 3, 5];++const stringsToNumbers = mapArray(strings, str => parseInt(str));+expect(stringsToNumbers).toEqual(numbers);+type test_stringsToNumber = Expect<Equal<+ typeof stringsToNumbers,+ number[]+>>;++const numbersToStrings = mapArray(numbers, num => `${num}`);+expect(numbersToStrings).toEqual(strings)+type test_numbersToStrings = Expect<Equal<+ typeof numbersToStrings,+ string[]+>>;++const numbersToNumbers = mapArray(numbers, num => num + 1);+expect(numbersToNumbers).toEqual([2, 2, 3, 4, 6])+type test_numbersToNumbers = Expect<Equal<+ typeof numbersToNumbers,+ number[]+>>;++const stringsToStrings = mapArray(strings, str => `${str}!`);+expect(stringsToStrings).toEqual(['1!', '1!', '2!', '3!', '5!'])+type test_stringsToStrings = Expect<Equal<+ typeof stringsToStrings,+ string[]+>>;diff --git a/challenges/generic-function-arguments/tsconfig.json b/challenges/generic-function-arguments/tsconfig.jsonnew file mode 100644index 00000000..875cb600--- /dev/null+++ b/challenges/generic-function-arguments/tsconfig.json@@ -0,0 +1,3 @@+{+ "compilerOptions": {}+}diff --git a/challenges/generic-function-arguments/user.ts b/challenges/generic-function-arguments/user.tsnew file mode 100644index 00000000..e9faf943--- /dev/null+++ b/challenges/generic-function-arguments/user.ts@@ -0,0 +1,3 @@+const identity = undefined;++const mapArray = (arr, fn) => arr.map(fn);\ No newline at end of filediff --git a/challenges/generic-type-arguments/prompt.md b/challenges/generic-type-arguments/prompt.mdindex ec3f5fe2..121dbac1 100644--- a/challenges/generic-type-arguments/prompt.md+++ b/challenges/generic-type-arguments/prompt.md@@ -10,7 +10,7 @@ Instead of using parenthesis to pass arguments, with generics we use angled bracOther than that, there are a lot of similarities between the two concepts.-> You can even provide defaults for generic arguments! See the relevant challenge for [generic defaults](todo-link).+> You can even provide defaults for generic arguments! See the relevant challenge for [generic defaults](https://typehero.dev/challenge/default-generic-arguments).There are two separate situations when you'd use this syntax. One is when you're working strictly with types, and another is when you're doing more normal JavaScript-y stuff like with functions and constants.@@ -86,7 +86,7 @@ type AvocadoToast = {}```-> Note: you might notice that we're missing types for our type arguments! Right now there's nothing stopping us from sending in wrong values like `GroceryItem<number[], boolean, { over: 9000 }>`. We'll cover that in a future challenge on [`generic-constraints`](todo-link).+> Note: you might notice that we're missing types for our type arguments! Right now there's nothing stopping us from sending in wrong values like `GroceryItem<number[], boolean, { over: 9000 }>`. We'll cover that in a future challenge on [generic type constraints](https://typehero.dev/challenge/generic-type-constraints).## Solving This Challengediff --git a/challenges/generic-type-constraints/prompt.md b/challenges/generic-type-constraints/prompt.mdindex a4d5250e..1bebf0fe 100644--- a/challenges/generic-type-constraints/prompt.md+++ b/challenges/generic-type-constraints/prompt.md@@ -1,6 +1,6 @@## The Problem Generic Type Constraints Solve-Generics are an incredibly powerful tool in TypeScript. In a [previous challenge](todo-generic-type-arguments) where generic type arguments were introduced, we compared them to function arguments _but for types_.+Generics are an incredibly powerful tool in TypeScript. In a [previous challenge](https://typehero.dev/challenge/generic-type-arguments) where generic type arguments were introduced, we compared them to function arguments _but for types_.Consider the parallel of these two:diff --git a/challenges/index-signatures/prompt.md b/challenges/index-signatures/prompt.mdindex 173f51bc..e7a076bf 100644--- a/challenges/index-signatures/prompt.md+++ b/challenges/index-signatures/prompt.md@@ -73,9 +73,9 @@ So wrapping it all up, our type for this API might look like this:```tstype Info = {- count: number;- currentPage: number;- pages: number;+ count: number;+ currentPage: number;+ pages: number;}type FollowerCountByUserResults = {@@ -83,8 +83,8 @@ type FollowerCountByUserResults = {}type FollowerCountByUser = {- info: Info;- results: FollowerCountByUserResults;+ info: Info;+ results: FollowerCountByUserResults;}```diff --git a/challenges/indexed-types/prompt.md b/challenges/indexed-types/prompt.mdindex 8531991c..db4c02c8 100644--- a/challenges/indexed-types/prompt.md+++ b/challenges/indexed-types/prompt.md@@ -86,7 +86,7 @@ type IndexEmpty = Empty[9001];Not a big deal or anything, but just something to be aware of in case you were expecting a different behavior.-> _spoiler alert_: there actually _ARE_ ways to index a string and return a particular character, but ends up involving some quite advanced type machinery. Check out the [First Character](todo-first-character) challenge if you're curious.+> _spoiler alert_: there actually _ARE_ ways to index a string and return a particular character, but ends up involving some quite advanced type machinery.<!-- Check out the [First Character](todo-first-character) challenge if you're curious. -->## Solving This Challengediff --git a/challenges/literal-types/prompt.md b/challenges/literal-types/prompt.mdindex df48d4de..c356892f 100644--- a/challenges/literal-types/prompt.md+++ b/challenges/literal-types/prompt.md@@ -1,6 +1,6 @@## The Problem Literal Types Solve-JavaScript, like most programming languages has a concept of [primitive data types](todo-primitive-data-types). Primitive data types are things like `string`, `boolean`, `number`, and `object`.+JavaScript, like most programming languages has a concept of [primitive data types](https://typehero.dev/challenge/primitive-data-types). Primitive data types are things like `string`, `boolean`, `number`, and `object`.> side note: in JavaScript, arrays and functions are actually objects, but that's a topic for another time :)diff --git a/challenges/metadata.schema.json b/challenges/metadata.schema.jsonindex f435a420..fe7f1092 100644--- a/challenges/metadata.schema.json+++ b/challenges/metadata.schema.json@@ -4,12 +4,12 @@"properties": {"id": {"description": "a snake-case-style slug that will also be used in URLs (and, therefore, needs SEO considerations)",- "maxLength": 25,+ "maxLength": 35,"type": "string"},"label": {"description": "A few capitalized words (often just a capitalized version of the slug) that the user will see for the challenge.",- "maxLength": 25,+ "maxLength": 35,"type": "string"},"description": {diff --git a/challenges/notes to dimitri.md b/challenges/notes to dimitri.mdindex 8da78d36..2bffaece 100644--- a/challenges/notes to dimitri.md+++ b/challenges/notes to dimitri.md@@ -31,9 +31,16 @@## TODO- figure out patching `Pick` out (`noLib`?)-- JSON Schema for metadata.json- add some kind of tags system to metadata+- CI+ - lint tests+ - lint markdown+ - spelling+ - lint code in markdown codeblocks+ - check for dead links somehow (might require local links to work)+ - schema validation+ - also check that the linked ids are correct (`prerequisites`)## random disorganized snippets for laterdiff --git a/challenges/type-aliases/prompt.md b/challenges/type-aliases/prompt.mdindex 484536df..39453d0b 100644--- a/challenges/type-aliases/prompt.md+++ b/challenges/type-aliases/prompt.md@@ -49,7 +49,7 @@ Wait! What's going on? `landSpacecraft` specifically asked for `Meters` but clBe careful that you understand that TypeScript is a _structural type system_. One result of this is that primitive types are _not_ something known as ["opaque types"](https://en.wikipedia.org/wiki/Opaque_data_type). To TypeScript, everything that's an alias for a number is still a number.-There actually is a idiomatic TypeScript way to design this, but it requires another concept covered in another challenge [`type-unions`](TODO-link).+There actually is a idiomatic TypeScript way to design this, but it requires another concept covered in another challenge on [type unions](https://typehero.dev/challenge/type-unions).## How To Create Type Aliasesdiff --git a/challenges/type-unions/prompt.md b/challenges/type-unions/prompt.mdindex 1102a195..29ecf8f6 100644--- a/challenges/type-unions/prompt.md+++ b/challenges/type-unions/prompt.md@@ -11,7 +11,7 @@ const landSpacecraft = (distance: Meters) {}```-But we noticed when we call `landSpacecraft` with the wrong literal type (see [the challenge on literal types](todo-link)), there's no error like we might expect:+But we noticed when we call `landSpacecraft` with the wrong literal type (see [the challenge on literal types](https://typehero.dev/challenge/literal-types)), there's no error like we might expect:```tsconst distanceInMiles: Miles = 1242;diff --git a/challenges/typeof/prompt.md b/challenges/typeof/prompt.mdindex e4eb9eff..a8232783 100644--- a/challenges/typeof/prompt.md+++ b/challenges/typeof/prompt.md@@ -6,7 +6,7 @@ You're doing yourself a great service by improve your knowledge of TypeScript.| | JavaScript world | types world || - | - | - |-| variables | `const`, `let`, function arguments | [type aliases](todo-type-aliases), [default generic arguments](todo-default-generic-arguments) |+| variables | `const`, `let`, function arguments | [type aliases](https://typehero.dev/challenge/type-aliases), [default generic arguments](https://typehero.dev/challenge/default-generic-arguments) || operations | `for` loops, `while` loops, recursion, higher-order functions | recursion, higher-order types || runtime artifacts | ✅ | ❌ || time of error | runtime | compile time |@@ -84,7 +84,7 @@ type CreatePoint = typeof createPoint//|TypeScript stuff```-Later, you're going to learn about ways to then do more operations on types. We're going to be extracting [keys of objects](todo-pick), and creating new types for [return types](todo-return-types) and [parameters](todo-parameters) of functions.+Later, you're going to learn about ways to then do more operations on types. We're going to be extracting keys of objects <!-- todo [keys of objects](https://typehero.dev/challenge/object-keys)-->, and creating new types for return types <!-- todo [return types](https://typehero.dev/challenge/return-types) --> and parameters <!-- todo [parameters](https://typehero.dev/challenge/parameters) --> of functions.## Solving This Challenge