diff --git a/snippets/snippets/todo/frtm.ts b/snippets/snippets/todo/frtm.ts new file mode 100644 index 0000000..d18fb64 --- /dev/null +++ b/snippets/snippets/todo/frtm.ts @@ -0,0 +1,11 @@ +type Todo = { + id: number + text: string + done: boolean +} + +// Make sure that the input and the output +// is of the correct type +function toggleTodo(todo: Todo): Todo { + // ... +} diff --git a/snippets/snippets/todo/npah.ts b/snippets/snippets/todo/npah.ts new file mode 100644 index 0000000..28cfff3 --- /dev/null +++ b/snippets/snippets/todo/npah.ts @@ -0,0 +1,11 @@ +type Todo = { + readonly id: number + readonly text: string + readonly done: boolean +} + +function toggleTodo(todo: Todo): Todo { + // This won’t compile + todo.done = !todo.done + return todo +} diff --git a/src/lib/snippets.ts b/src/lib/snippets.ts index b12fea1..3da8feb 100644 --- a/src/lib/snippets.ts +++ b/src/lib/snippets.ts @@ -502,6 +502,18 @@ export const dxfc = `// Associated data. If we're using React, this { id: 2, text: 'Second todo', done: false } ]` +export const frtm = `type Todo = { + id: number + text: string + done: boolean +} + +// Make sure that the input and the output +// is of the correct type +function toggleTodo(todo: Todo): Todo { + // ... +}` + export const lieq = `type Todo = { id: number text: string @@ -527,6 +539,18 @@ export const njgr = `function toggleTodo(todo: Todo): Todo { return todo }` +export const npah = `type Todo = { + readonly id: number + readonly text: string + readonly done: boolean +} + +function toggleTodo(todo: Todo): Todo { + // This won’t compile + todo.done = !todo.done + return todo +}` + export const ntau = `function toggleTodo(todo: Todo): Todo { // Little Duckling’s code from earlier: // Missing the "id" property diff --git a/src/pages/todo.tsx b/src/pages/todo.tsx index beb8c43..aae3d9d 100644 --- a/src/pages/todo.tsx +++ b/src/pages/todo.tsx @@ -634,7 +634,7 @@ const Page = () => ( children: ( <>
- Oops, I did it again!
- No worries! The question is,{' '}
+ No worries, Little Duckling! The question is,{' '}
So far, we’ve learned the following:
+
+
+ 1. We can define a type to make sure that the input
+ and the output of a function is of the correct type.
+
+
+
+ 2. We can use the readonly keyword to make sure
+ that an object property is not modified.
+
+
+ Before TypeScript, you needed to write unit tests to verify these
+ things. So in a sense,{' '}
+
Next, let’s take a look at more non-trivial examples!
+ > + ) + }, // { // title: ( // <>