Use Pick and Omit to Reshape TypeScript Object Types
lesson
Reshape your object types in TypeScript using Pick and Omit. Keep your code DRY, consistent, and easier to maintain.
Browse
Find courses, lessons, articles, talks, and podcasts.
80 resources
Showing 1–24 · Page 1 of 4
lesson
Reshape your object types in TypeScript using Pick and Omit. Keep your code DRY, consistent, and easier to maintain.
lesson
Learn to avoid type bugs in TypeScript by understanding when to use foo?: string vs foo: string | undefined. Clear examples & best practices.
article
TypeScript can sometimes feel like bunch of nonsense. But once you internalize a few key patterns, the type system starts to feel like a powerful tool instead of an obstacle. Here are a few tricks that I’ve personally found valuable, especially if you’re working on a large codebase or building libraries. --- ## 1. Optional Keys vs Optional Values There’s a big difference between marking a property as optional and allowing `undefined` as a value. These look similar: ```ts type OptionalKey = { foo?: string; } type OptionalValue = { foo: string | undefined; } ``` But they behave differently: * `foo?: string` means the key `foo` might not be present at all. * `foo: string | undefined` means `foo` is always present, but its value might be `undefined`. Why this matters? The difference between them affects the way you use it: * How you check if a property exists * Function argument inference * Serializing/deserializing data from external sources ### Example ```ts function logFoo(obj: OptionalKey) { if ('foo' in obj) { console.log(obj.foo?.toUpperCase()); } } function logBar(obj: OptionalValue) { console.log(obj.foo?.toUpperCase()); // May log undefined } ``` As a rule of thumb, use `foo?: Type` (Optional Key) when the property might not be present, and `foo: Type | undefined` (Optional Value) when the key is always expected. --- ## 2. Pick and Omit for Object Key Manipulation When you need to reshape object types by including or excluding specific keys, `Pick` and `Omit` are your go-to tools. This type utilities are part of the language and are always available for your use, they are particulary useful when you need to derive types. > Don't forget, Pick and Omit works over Object shapes ### Pick ```ts type User = { id: number; name: string; email: string; }; type PublicUser = Pick<User, 'id' | 'name'>; // { id: number; name: string } ``` `Pick` is useful when exposing a public-facing API without leaking sensitive fields, it lets you choose what properties will be included ### Omit ```ts type PrivateUser = Omit<User, 'email'>; // { id: number; name: string } ``` Use `Omit` when you want to reuse a base type but remove some fields for specific scenarios, like forms or UI display logic. These utilities keep your types DRY and consistent. Instead of redefining structures, you can derive them from existing ones, reducing duplication and potential errors. --- ## 3. Extract and Exclude for Union Filtering Unlike `Pick` and `Omit`, which work on object keys, `Extract` and `Exclude` operate on union types, they are pretty similar in how the work. ### Extract ```ts type Status = 'draft' | 'published' | 'archived'; type ArchivedOnly = Extract<Status, 'archived'>; // 'archived' ``` Use `Extract` when you want to narrow down a union to only include specific members. ### Exclude ```ts type VisibleStatus = Exclude<Status, 'archived'>; // 'draft' | 'published' ``` Use `Exclude` when you want to remove one or more members from a union. These are essential tools when refining API responses, filtering variants, or creating conditional logic that needs to type-check specific string literal options. --- ## 4. Loose Autocomplete This is a different kind of trick, this one affects how your editor understand your types. Sometimes you want to offer a set of suggestions to the user without forcing them to pick from a fixed list. ### The trick ```ts type Variant = 'success' | 'warning' | 'info' function setVariant(variant: Variant | (string & {})) { // ... } ``` Now TypeScript will offer autocompletion for the variants defined in the `Variant` union, but will also allow allow any other string. `string & {}` is essentially still a string, but TypeScript treats it as a branded version, preserving autocomplete while keeping it assignable to `string`. > [Here](https://egghead.io/blog/using-branded-types-in-typescript) you can found another article related to [Branded Types](https://egghead.io/blog/using-branded-types-in-typescript) ### Use cases * Props with suggested values * Config objects * Third-party data with flexible inputs --- ## 5. Mapped Types for Smart Rewrites Mapped types let you create new types from existing ones by transforming each property. This concept is a cornerstone of TypeScript’s type system and is covered more deeply in my article: [Learn the Key Concepts of TypeScript’s Powerful Generic and Mapped Types](https://egghead.io/blog/learn-the-key-concepts-of-typescript-s-powerful-generic-and-mapped-types). You can consider Mapped types as some kind of function that transform a type in another by using all of the utilities and features of Typescript, like the above utilities and tricks, but also string literals, and more. ### Example: feature flags ```ts type Config = { debug: string; logging: string; }; type FeatureFlags = { [K in keyof Config]: boolean; }; // This will create the following type // { debug: boolean; logging: boolean } ``` ### General Utility Type ```ts type Booleanize<T> = { [K in keyof T]: boolean; }; ``` Mapped types are perfect for: * Adapting backend responses * Creating flexible utility types * Rewriting shapes while preserving keys * Enforcing contracts between layers They’re also essential in combination with generics to create reusable type logic across your app or library. > Found more about Generics in the following article [An Introduction to Typescript Generics](https://egghead.io/blog/an-introduction-to-typescript-generics) --- ## 6. The IIMT Pattern (Infer Inside Mapped Type) This pattern unlocks the power of `infer` within mapped types, allowing you to extract and reuse internal type information from complex structures. It dynamically inspects each property of a type (by using `infer`), and if that property matches a specific shape (e.g., a function), it extracts part of it. This means you can build new types that are entirely based on the structure of other types without manually copying anything. ### The pattern ```ts type API = { getUser: () => Promise<{ name: string }>; logout: () => void; }; type ReturnTypes<T> = { [K in keyof T]: T[K] extends (...args: any) => infer R ? R : never; }; // Result: // { // getUser: Promise<{ name: string }>; // logout: void; // } ``` Here, ReturnTypes iterates over each key in the API object and uses conditional types to check if the value is a function. If it is, it uses infer R to grab the return type of that function. ### How it works - `keyof T` iterates over each key of the input type. - `T[K]` accesses the value type at each key. - `T[K] extends (...args: any) => infer R` checks if that value is a function. (consider this as a conditional block) - `infer R` captures the return type of the function. - If the value is not a function, the fallback is never. This pattern is composable—you can use it to build return type maps, argument type maps, or anything else you need. ```ts type ArgumentTypes<T> = { [K in keyof T]: T[K] extends (...args: infer A) => any ? A : never; }; ``` This will give you a type with the argument list of each function in a mapped type. You can use this in different situations like: - Generating automatic schemas - Building strongly-typed service clients - Rewriting function maps - Validating types without duplicating logic If you’re building libraries or dynamic APIs, this pattern is a must-have in your TypeScript toolbox. Once it clicks, it opens the door to expressive, scalable, and maintainable type logic.
article
<ArticleSeriesList resource="svelte-series" /> # Form Actions The next concept to review in this beginners guide are forms. Forms are an essential part of every web application, they are the “native” way to capture user information and perform data mutation. The `form` element is the way to denote that the page will have a list of form controls. This element can use some attributes to describe the `form` behavior. - `action` This attribute defines the location where the form will send the collected data. - `method` Is the way to define what HTTP method will be used to send the data to the `action` location. SvelteKit uses this as the default way to handle communication between front-end and back-end. SvelteKit defines the concept as **Form Actions** These are a set of functions defines inside a server side code like `+page.server.js` that declares how the data will be captured and what to do with the data. The function should be placed as part of an object named `actions` that needs to be exported: ```jsx // src/routes/+page.server.js // this is a convenience function to return errors import { fail } from '@sveltejs/kit'; // A well known/reserved export that // describe how a form will be handled /** @type {import('./$types').Actions} */ export const actions = { default: async ( { request }) => { // read the form data sent by the browser const formData = await request.formData() const title = formData.get('title'); const description = formData.get('description'); const priority = formData.get('priority') // Perform some backend code/logic action const item = await saveTodoItem(title, description, priority) if (!item) { return fail(401, { message: 'Invalid data' }) } return { success: true }; } } ``` The above is an example of a form action that: - retrieves the form data sent using `formData()` - Gets the fields from the `formData` Map. The fields name are the same used in the `name` attribute in the html form - Execute a back-end operation like saving the data into a database - Triggers an error if the user was not found, marking the error as 401. - return success if all went good But why are we doing it this way? Well, the other option is more verbose that will be to create an API endpoint that is triggered when it receives a POST request, this can be done by creating a `+server.ts` file at the route and exporting a function named `POST`. > The `actions` object exported from the server side code can hold many actions to handle many forms. To do that you’ll have to define multiple keys inside the object and remove the `default` action. If you name your actions, for example `addTodo` instead of `default` the `action` attribute of the form will have to be replaced by adding the name of the action to perform: `action="?/addTodo` > Form Actions is a simpler way to handle a form directly in the server side code, the communication between this back-end code and the corresponding page/svelte component is handled by SvelteKit, all you need to do is to create a form in the `+page.svelte` file like the following ```html <script> /** @type {import('./$types').PageData} */ export let data; const options = [1,2,3,4,5] </script> <h1>{data.title}</h1> <div>{@html data.content}</div> <form method="POST" action="/"> <input type="text" name="title" placeholder="TODO title" /> <input type="text" name="description" /> <select name="priority"> {#each options as option} <option value={option}>{option}</option> {/each} </select> <button type="submit">Create Item</button> </form> ``` That form will automatically (and natively) communicate with the default form action exported from the sibling `+page.server.ts` in there you have access to all the required server side code to perform any operation you would need. > Form Actions feels magical but they’re just a URL that invokes a function. > But, the default behavior of forms is to send the data and refresh the page, that doesn’t feel right nowadays, that is why SvelteKit offers a way to perform **progressive enhancement** <EmailSubscribeWidget /> ## Progressive enhancement The default behavior of form and form actions is to work without requiring JavaScript, just simple HTML form that send data over the wire. This makes your application more resilient to the many things that can go wrong on different devices. But, if all goes well, the experience of using forms without JavaScript is not desirable, how can you improve it? SvelteKit comes with [a svelte action](https://svelte.dev/tutorial/actions) named `enhance` that does exactly what the name implies. It enhances the user experience of the form, by just adding the action into the form tag you have a fully working form that will not refresh the page when you send the data, but if for some reason the JavaScript is not loaded yet, it will still work. ```html <script> import { enhance } from '$app/forms' /** @type {import('./$types').PageData} */ export let data; const options = [1,2,3,4,5] </script> <h1>{data.title}</h1> <div>{@html data.content}</div> <form method="POST" action="/" use:enhance> <input type="text" name="title" placeholder="TODO title" /> <input type="text" name="description" /> <select name="priority"> {#each options as option} <option value={option}>{option}</option> {/each} </select> <button type="submit">Create Item</button> </form> ``` When the form is submitted the `use:enhance` action takes over performing the following - Update the `form` property and `$page.form` and `$page.status` stores. - Reset the `<form>` element and rerun the `load` function associated to the page The default behavior of the action can also be customize to your liking. The action accepts a callback function that will run before the form is submitted. ```html <script> // import the enhance action import { enhance } from '$app/forms' // This is the page data returned by the load function /** @type {import('./$types').PageData} */ export let data // This is the form property that gives you access to the form status export let form // This is the function that will run before the form is submitted /** @type {import('$app/forms').SubmitFunction} */ function addTodo(input){ // do something before the form submits console.log(input) return async (options) => { // do something after the form submits console.log(options) } } </script> <!-- ... --> ``` This function returns an asynchronous function meant to run after the form is submitted. Through this function `input` argument you have access to: - `action` to get access to the URL details to which the form is posted - `cancel` a method to call to prevent form submission - `formElement` gives you direct access to the `<form>` element - `formData` references the `FormData` object as the data that is about to be submitted - `submitter` is the `HTMLElement` that caused the form to be submitted The arguments for the return function are - `action` again, it gives you access to the URL details - `form` gives you access to the `<form>` element - `result` an `ActionResult` object that will give you access to the response data - `update` is a function that runs the regular logic of the form, if you don’t call it you’ll have to execute the logic by yourself. The first thing that most developer will want to add to any form is a loading state, how can you do that for this form?. By simple creating a `loading` state variable that will be updated by the submit function used by the `enhance` action. ```html <script> import { enhance } from '$app/forms' /** @type {import('./$types').PageData} */ export let data; const options = [1,2,3,4,5] // Create a loading state variable let loading = false /** @type {import('$app/forms').SubmitFunction} */ function addTodo(input){ // before the form is submitted set the loading state to true loading = true return async ({ update }) => { // After the response returns update the loading state to false loading = false await update() } } </script> <h1>{data.title}</h1> <div>{@html data.content}</div> <form method="POST" action="/" use:enhance={addTodo}> <input type="text" name="title" placeholder="TODO title" /> <input type="text" name="description" /> <select name="priority"> {#each options as option} <option value={option}>{option}</option> {/each} </select> <button type="submit" disabled={loading}> {#if loading} Creating... {:else} Create Item {/if} </button> </form> ``` # Let’s store new todo items in a database The form actions are exported from the `+page.server.js` file allow you to perform server side code with ease, like accessing a database instance > Remember from previous chapter, the `+page.server.js` file execute code only on the server and `+page.js` file execute the code both server and client > Let’s use what we know until now continue working in the TODO application allowing the user to, create a todo item, store that into a database and also retrieve all the items to show them in the page. First, let’s check the current state of the application, the file tree should look something like this: ```html src └──routes ├── +layout.svelte ├── +page.svelte └── todo ├── [id] │ ├── +page.js └── └──+page.svelte ``` Let’s open the root `+page.svelte` file to add the corresponding form, it should look the same as the previous example. Then, create the server side file `+page.server.js` let’s add a basic `load` function and the default form action as seen before. > You can also name the files as `+page.server.ts` to work with Typescript  The code of this file is also the same as seen before: - a `load` function that returns dummy content - an `actions` object that defines the `default` action, it reads the data from the form and perform a function named `saveTodoItem` that you need to implement. The idea now is to be able to store the data received by the action into a database, for this example I choose to use `sqlite` but you can choose anything you want and will behave very similar. The next steps will be: - install dependencies `pnpm add better-sqlite3` - Create the sqlite database through the cli - Create a new file to hold the database setup and logic under `src/lib/sqlite.js` To setup the database and tables that the application will use just open the CLI, make sure you are located at the root of the project and execute: ```jsx $ sqlite todos.db sqlite > CREATE TABLE items ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, description TEXT NOT NULL, priority INTEGER NOT NULL); ``` That will create a table inside the sqlite database named `items` with the following keys: `id` as primary key and `title` and `description` as text and finally `priority` as integer, same as the fields that are shown in the form. With the table created, time to go back to the code, create the file `src/lib/sqlite.js` this file will hold the database setup and helper function to store and retrieve information ```jsx import Database from 'better-sqlite3' const db = new Database('todos.db') db.pragma('journal_mode = WAL') /** * @typedef {{ title: string, description: string, priority: number }} TodoItem */ /** * @param item {TodoItem} */ export function saveTodoItem(item) { const sql = db.prepare(`INSERT INTO items (title, description, priority) VALUES (?, ?, ?)`) const info = sql.run(item.title, item.description, item.priority) return info.changes } export function getTodoItems() { const sql = db.prepare(`SELECT * FROM items`) return sql.all() } /** * @param id {number} */ export function getTodoItem(id) { const sql = db.prepare(`SELECT * FROM items WHERE id = ?`) return sql.get(id) } ``` The file export 3 functions that allows you to insert items into the database, retrieve all of them and retrieve one identified by the id. Now, you can use them inside the `+page.server.js` file by importing the `saveTodoItem` function from `$lib/sqlite` to be able to save the data and also importing `getTodoItems` to use it in the `load` function, now the file will looks like this ```jsx import { fail } from '@sveltejs/kit'; import { saveTodoItem, getTodoItems } from '$lib/sqlite'; /** @type {import('./$types').PageLoad} */ export async function load({ params }) { const items = await getTodoItems() return { title: `This title comes from some other logic`, content: `This was server rendered`, items }; } /** @type {import('./$types').Actions} */ export const actions = { default: async ({ request }) => { // read the form data sent by the browser const formData = await request.formData() const title = formData.get('title').toString() const description = formData.get('description').toString() const priority = formData.get('priority').toString() // Perform some backend code/logic action const item = await saveTodoItem({ title, description, priority: parseInt(priority,10) }) if (!item) { return fail(401, { message: 'Invalid data' }) } return { success: true }; } } ``` Now, last step will be to update the page component to list the items returned by the load function by adding a table at the bottom like the following ```html <table> <thead> <tr> <th>Id</th> <th>Title</th> <th>Description</th> <th>Priority</th> </tr></thead > <tbody> {#each data.items as item} <tr> <td>{item.id}</td> <td><a href={`/todos/${item.id}`}>{item.title}</a></td> <td>{item.priority}</td> </tr> {/each} </tbody> </table> ``` This table will render the data that comes inside the `data` property, it will also show you a link to navigate to that item page. Do you remember that in previous chapter you created a dynamic route under `todo/[id]` ?, Let’s work on that page to retrieve just one todo item. The current status of that page is the following ```html <script> /** @type {import('./$types').PageData} */ export let data; $: console.log(data) </script> <h1>This is the TODO item {data.id}</h1> <p>Here I'll show the contents of this item</p> ``` This route defines a `+page.js` file but that runs both on the server and client, we need to run only server code to retrieve the database data, rename that file to `+page.server.js` and let’s add the logic to get the data ```jsx import { getTodoItem } from '$lib/sqlite' /** @type {import('./$types').PageLoad} */ export async function load({ params }) { const item = await getTodoItem(params.id) return { id: params.id, item, } } ``` Straightforward code, just grab the `id` from the url parameters (the dynamic part) and use that to retrieve the item from the database with the helper function created before. Now, on the page side, let’s display the information. ```html <script> /** @type {import('./$types').PageData} */ export let data; $: console.log(data) </script> <h1>This is the TODO item {data.id}</h1> <h2>Title: {data.item.title}</h2> <p>Description: {data.item.description}</p> <p>Priority: {data.item.priority}</p> ``` And that is all you need. Now, the challenge for this step will be to update this page to allow the users to update a todo item, that means: - Adding a form that shows as default values the current state of the todo item - Adding a new form action to handle the update - show the updated data in the page You can also make the pages prettier by adding styling using the `<style>` tag, TailwindCSS classes, or anything else you’d like. At this point you now all that you need to kick start your journey developing applications with SvelteKit, there are more to uncover as you progress with it so stay tuned for more articles where we will delve into more advanced topics. <EmailSubscribeWidget />
article
<ArticleSeriesList resource="svelte-series" /> In the previous articles, we covered the first cornerstone of building an application with SvelteKit, you now know how to setup a new project and how add routes, even dynamic routes, but that alone doesn’t create **an application**, there is one more thing to do. The next concept or feature that we need to review is the process of data loading, or how SvelteKit injects data into the pages. Remember, each route folder can have a `+page.svelte` file that defines the page to be rendered, but at the same time it can have a `+page.js` file. This file is in charge of defining the required logic to retrieve some data and to export a **well-known** function named `load`. **Whichever is returned by this function inside the `+page.js` file will be available as data into the sibling `+page.svelte` file:** ```jsx /** @type {import('./$types').PageLoad} */ export function load({ params }) { return { title: `This title comes from some other logic`, content: `This was server rendered` }; } ``` The example code above shows the structure of the `load` function inside the `+page.js` file. **It’s just a function that returns an object.** The return value of this function will be available in the page code as `data`. > Is worth noting that the name of this function is **reserved** by SvelteKit and that this file can’t export other functions (there are a few more reserved ones that can be exported that we will cover in future chapters) > ```jsx <script> /** @type {import('./$types').PageData} */ export let data; </script> <h1>{data.title}</h1> <div>{@html data.content}</div> ``` > The types used in this examples (written as JSDoc) are generated by sveltekit, in this way you get full type safety across the wire. > Is worth noticing that the `load` function here will run both on the server and in the browser, this means that this `load` function can hold any server side-only code as database direct access. <EmailSubscribeWidget /> ### What if I need to access a database? Well, sometimes you need to only execute code on the server, for that you can use another `+` prefixed file. the `+page.server.js` (or `.ts` if you prefer.) This reserved named file works exactly as `+page.js` but will run code only on the server: ```jsx // src/routes/topic/[topic]/+page.server.js import { error } from '@sveltejs/kit' import db from '$lib/database' /** @type {import('./$types').PageServerLoad} */ export async function load({ params }) { try { const {title, content} = await db.getPost(params.slug) return { post: { title, content, } }; }catch(err){ throw error(500, err) } } ``` You can see in the example above that now, you can use server side reserved code, with a very similar structure, the only addition here is that now, the function needs to be `async` and because of that it can fail. To guard ourselves against the possible failure the code is wrapped within a `try/catch` block. If something goes wrong an error is thrown using the `error` function. > There is a default error page on SvelteKit but you can customize that to your liking by adding an `+error.svelte` file to some of the routes. This component will act in a similar way as the layout one, affecting all the nested routes underneath. > To load this data into the the sibling `+page.svelte` you’ll do same as before: ```jsx <script> /** @type {import('./$types').PageData} */ export let data; </script> <h1>{data.post.title}</h1> <div>{@html data.post.content}</div> ``` Let’s go back to our application, a this point the current file structure should looks like the following: ```jsx src └──routes ├── +layout.svelte ├── +page.svelte └── todo ├── [id] │ ├── +page.js └── └──+page.svelte ``` Layouts can also load data We already review the concept of layouts, an svelte component that can wrap pages, with shared structure, like a navigation bar, but what happens if you need to load data that can be used in many pages?. **You can use the layout to pass data to the child pages.** The `+layout.svelte` behaves in a similar way as the `+page.svelte` it can load data through the sibling reserved file `+layout.js` (o `. ts`) that will export a `load` function that will run on client and server, or using server-only code through `+layout.server.js`. The data returned through the layout `load` function will be available to every child route (remember, layouts will affect every nested route). Let’s add a new `+layout.server.js` file at the root level: ```jsx /** @type {import('./$types').LayoutServerLoad} */ export async function load({ page }) { const res = await fetch(`https://api.example.com/data`); const articles = await res.json(); return { articles, }; } ``` The `load` function fetches data from an API and returns it as an object. The returned data will be available to every child route that uses the layout. Now, let’s update the root layout component on `+layout.svelte` : ```html <script> // Global CSS import "../app.css" /** @type {import('./$types').LayoutData} */ export let data; </script> <nav> <a href="/">Home</a> <a href="/blog">Blog</a> </nav> <main> <ul> {#each data.articles as item} <li>{item.title}</li> {/each} </ul> <slot /> </main> <footer> This is the footer </footer> ``` Now the `+layout.svelte` component receives the `data` from the `load` function and would render the data onto the screen. Until this point, we reviewed how SvelteKit handle unidrectional data flow, there is a more advanced way to access your data by using the `$page` store. We will review this process in the next article of the series! <ResourceWidget resource="next-up"/> <EmailSubscribeWidget />
article
<ArticleSeriesList resource="svelte-series" /> In the previous chapter of this series we reviewed what SvelteKit is and what it offers to the ecosystem. We also learned how to setup a base application and review one of the main core concepts of the framework: **Routing**. Routing is essential on any web application. It’s how the application organizes the code to make it work for the web world that is based on URL routes. In this chapter we will dive a bit deeper onto the routing system used by Svelte, will learn about the different files available, how they work and what uses cases each them have. At the same time we will start building the TODO application along the way. Let’s get started! --- ## File System Router The heart of the framework and the motor that get everything running is the novel filesystem-based router. I say novel because the main difference with other filesystem-based router solutions out there is that SvelteKit uses the **folders** inside the `src/routes` folder as the description of the route. > You can change `src/routes` to a different directory by editing the [project config](https://kit.svelte.dev/docs/configuration). > This means that - `src/routes` contains the root route - `src/routes/blog` create the `/blog` route - `src/routes/topics/[topic]` creates a route with the parameter `topic` for example `/topic/javascript` or `/topic/svelte`. Each folder inside `routes` can have or more **route files.** This files are represented by the `+` prefix. - `+page.svelte` defines a page under the route, it will contain the code to be rendered, an Svelte Component - `+page.js` This is another special file that will allow you to define the logic to perform data load process meant to be run before the page renders - `+page.server.js` This is a file marked to run only on the server, this means that you can write data loading logic that can only run in the serve, like database access.  > There are more files marked with the `+` prefix that will be reviewed later in the article > Let’s say you want to define your index page, the first page of your application. For that, you’ll create a `+page.svelte` under `src/routes`. This component is just an Svelte component like: ```html <!-- This is the home page --> <script> export let name = 'World'; </script> <h1>Hello {name}!</h1> <p>This is the homepage</p> ``` > Here's an example of what a SvelteKit home page might look like. This file is named `+page.svelte`. > ## Server Side Rendering (SSR) SvelteKit comes preconfigured to perform Sever Side Rendering (SSR), this means that the component will render twice, once in the server for the initial request and once in the client [(hydration process)](https://kit.svelte.dev/docs/glossary#hydration). Remember **a page in an SvelteKit application is just a Svelte Component that has SSR and hydration**. Let’s add a second route `src/route/todos/+page.svelte` this will be accessible when visiting the`/todos` route ```html <!-- This is the todos home page --> <h1>Welcome to my TODO list</h1> <style> h1 { font-size: 3rem; } </style> ``` > **Why does SveltekIt use this `+` prefix?** the `+` prefix is reserver for SvelteKit reserved files. The `+page.svelte` name is a reserver name allowing SvelteKit to ignore other files or components. This allows **you** to collocate code, utilities or components related to that page under the same folder structure. > Let’s imagine that these two files are part of your awesome new application, you fire up the console and run `pnpm dev`, and visit the [localhost](http://localhost) url where you can see the main route. But, how do you navigate to the blog pages? Remember this is just Svelte components! To allow users to navigate you can simply drop an anchor element pointing to the desired route: ```html <!-- This is the home page --> <script> export let name = 'World'; </script> <h1>Hello {name}!</h1> <p>This is the homepage</p> <a href="/todos">Visit my TODOS</a> ``` > Is important to note that SvelteKit use simple HTML anchor tag `a` to define the links for the application, there is no custom component around it, simple and effective. > ## The Layout Component Now your users can navigate from the root page to the blog page, but how they can come back? You’ll need to write an anchor tag on the other page too right? Is there a way to share structure among pages? The answer is **YES** the `+layout.svelte` file There is another reserver file name: `+layout.svelte`. Which is just another Svelte component. The main difference is that the layout component doesn’t create a page, but it creates as it names indicate a layout. **A way to share structure among child routes.** Each route folder can hold a `+layout.svelte` this component can render anything you need plus a `<slot />` . Each layout will wrap the `+page.svelte` components defined along it and under it. This means that if you create a layout under `src/route/+layout.svelte` it will become the root layout and will affect every other page created, exactly what we’re looking for: ```html <script> // Global CSS import "../app.css" </script> <nav> <a href="/">Home</a> <a href="/todos">TODOS</a> </nav> <main> <slot /> </main> <footer> This is the footer </footer> ``` Now every page will be rendered inside this layout at the `slot` place, so every page will have a navigation and a footer. > ``<slot />`` is a special Svelte component used to declares that component will receive some external content. You can think of it as the `children` prop in React. > ## Dynamic Routes Finally, let’s review that dynamic route, the one that receives a parameter and is named as `src/routes/todo/[id]` The first thing is to add a page to be able to see something in the browser, so let’s add a `+page.svelte` under it.  Here SvelteKit will render the content of this new `+page.svelte` every time the browser request a route that matches `/todo/<whatever>` This new page will inherit the same `+layout.svelte` as the previous ones, but you can add it’s own layout too by creating a new `+layout.svelte` file under the same folder. Let’s set the content of this file to show the `id` parameter. ```html <script> /** @type {import('./$types').PageData} */ export let data; </script> <h1>This is the TODO item {data.id}</h1> <p>Here I'll show the contents of this item</p> ``` Again, this is a simple Svelte component, but it have an special prop `data` `data` here is an special prop that SvelteKit exposes to allow you to retrieve information from the server side process, its typed or annotated as `PageData` . This type is created based on what the server side returns. This is the first encounter with the data loading approach that we will review deeper in the next chapter. <EmailSubscribeWidget /> ## Data Loading For now, let’s create a sibling file named `+page.js` This file is part of the data loading process, it will hold the required logic to retrieve data and pass that to the sibling svelte component that represents the page. **This file runs in the server and client during hydration.** The content of this file, for this step of the application will be very simple: ```jsx /** @type {import('./$types').PageLoad} */ export async function load({params}){ return { id: params.id } } ``` This is a very simple function, but there is a lot to unpack here, we will fully review the data loading process in the next chapter. This file exports a **well-known** function named as `load` this is a restricted name that SvelteKit use to perform data loading. This function have access to the url parameters defined when you created the route in this case the route was named as `routes/todo/[id]` therefore, the `params` argument there will have access to the `id` variable. By just returning an object, SvelteKit makes that `id` accessible inside the `data` prop in the svelte component. Go ahead and visit the site (remember to have the service running with `pnpm dev`), you’ll see something like this when visiting the url [`http://localhost:5173/todo/1`](http://localhost:5173/todo/1)  # Conclusion At this point, you learn how to create routes inside Sveltekit, each route is represented by a folder and inside that folder you’ll found an svelte component named as `+page.svelte` that represents the page that will be rendered when visiting that route in the browser. You also learn that you can share layout structure by create a `+layout.svelte` file inside a route. This layout will affect all the nested routes below it.´ Finally we reviewed how to create dynamic routes by naming the folder with `[]` square brackets, to have access to that url parameter you need to use a data loading function that lives inside the `+page.js` file, sibling to the page component inside that route. <ResourceWidget resource="next-up" /> <EmailSubscribeWidget />
article
<ArticleSeriesList resource="svelte-series" /> ## Introduction SvelteKit is a robust web application framework that offers a modern, component-based approach to building web applications. **SvelteKit can be considered the Next.js of Svelte.** In this guide, we'll take you through the basics of SvelteKit and show you how to build your own full-stack web applications from scratch. Whether you're a seasoned developer or just getting started in web development, this guide will provide you with everything you need to know to get up and running with SvelteKit. So let's get started! ### Why SvelteKit is an excellent choice for building web applications Before diving into how to work with SvelteKit, the first questions you should answer is why you should choose SvelteKit for your next project. SvelteKit offers several advantages and features that can be found in other frameworks, but you’ll get them here with a twist. - **Fast performance:** SvelteKit's compiled components run directly in the browser, resulting in faster load times and better performance overall. - **Easy to learn:** SvelteKit is based in Svelte, and the simple and intuitive syntax makes it easy to start building web applications, even if you're new to web development. - **Flexible and modular:** SvelteKit's component-based architecture makes it easy to build modular, reusable components that can be used across multiple projects. - **Server-side rendering:** SvelteKit supports server-side rendering out of the box, allowing you to easily build applications that can be optimized for SEO and provide better initial load times. - **Built-in routing:** SvelteKit includes built-in routing capabilities, making it easy to create complex, multi-page applications without the need for additional routing libraries. So, whether you want to tap on the power of SvelteKit because it clicks on you or just out of curiosity, this guide will help you get up to speed. But before diving into the code, let’s review some concepts to allow everyone to be on the same page. ## What is Svelte If you’re already familiar with Svelte, you can jump to this section; if not, stay around. It’s very similar to other Javascript Frameworks available today. The main difference with other tools like React or Vue is that Svelte doesn’t use the so-called “Virtual DOM”. In fact, Svelte is a language+compiler that takes the code you write in “the Svelte way” and creates a significantly optimized imperative code that directly manipulates the DOM as required. At some point, Svelte was known as “the magically disappearing framework” since after the application is built, there is no framework runtime inside your bundle. Another feature of Svelte is that it is **truly reactive,** this means that a simple change in a variable will immediately be reflected in the UI. As mentioned before, Svelte can be considered a language in its own right. It uses what is known as a Single File Component. This means that a component is represented by a single `.svelte` file, which contains the UI definition of the component. This is written in simple HTML. The dynamic and business logic of the component is written in plain old JavaScript. This is found between the `<script>` tags. Lastly, the style that will be applied (scoped) to the component is written between the `<style>` tags. In general, terms, if you're familiar with JavaScript, HTML, and CSS, you're ready to dive into Svelte: ```html <script> export let name = 'World'; </script> <h1>Hello {name}!</h1> <p class="paragraph">This is an styled paragraph</p> <style> .paragraph { color: red; } </style> ``` > This example is a simple Svelte component that takes in a `name` prop and displays a greeting. > ## Why Do I Need SvelteKit? While Svelte is an excellent framework for building web application UIs and provides you with a state-of-the-art Developer Experience, there are more complete solutions for building full-stack web applications. That's where SvelteKit comes in. When building a complete application, there are many moving parts that you need to handle, from routing to the data-loading process. SvelteKit packs all of that into a comprehensive tool that delivers an opinionated and optimized way of building such applications. When you build an application with SvelteKit, you’ll get a unified development experience that includes everything from server-side rendering to client-side routing, data fetching, and data mutation. <EmailSubscribeWidget /> ## Setting up a SvelteKit project. A few core concepts make up this framework, and we will dive deeper into each in the following articles of this series. In this article, you’re getting an overview and learning how to set up a project so that you have a solid foundation to work off of before going further. **The best way to learn new concepts is to get your hands dirty with code.** To accomplish that, let’s set up a new SvelteKit project, this will help you get a sense of how the framework works, and also, this setup will act as an overarching project that we will build on each article of the series. Let's create a new project using the following command in your terminal. ```bash $ npm init svelte@next sveltekit-todo-app ``` > Yes, we will build *another* TODO app. Why? Because the application requirements are well-known by everyone and are not complex, this will allow you to focus on the framework concepts and features instead of the application logic. > This command will show you a series of questions you must answer to generate the base application. Follow the prompt, and at the end, you’ll have a set of files and folders ready to be used. > **Important** the second question will ask you what type of scaffold you want. Choose "Skeleton project" . > --- ### Optional Step: Add TailwindCSS Configuration This is an optional step. You can add Tailwindcss configuration by using this [community package](https://github.com/svelte-add/svelte-add) ```bash $ cd sveltekit-todo-app $ npx svelte-add@latest tailwindcss $ npm install ``` This will configure Tailwind and install all the dependencies. --- Now, the project is ready. You can execute `npm run dev` in the terminal to run the application in development mode. Visit `http://localhost:5173` in the browser to see the result. Not impressive at this point. Remember, you just setup the skeleton of an app. Let’s review the files and folders that were created  The image above shows all the files generated by the script. We will review and manipulate mostly of those living inside the `src` folder. The SvelteKit’s routing system is a file system approach to define a route. You need to create a **folder** inside the `src/routes` folder. Each folder you create there can have one or more **route files.** These files have a special naming convention. They all use the `+` prefix. In the image above, you can see one of those special files, the `+page.svelte` file that lives in the root of `src/routes`. That file represents the `root` route, your “index” route. This `+page.svelte` files are just svelte components that get rendered as a page in the browser. Go ahead and update the contents of `+page.svelte`: ```html <h1>Welcome to SvelteKit</h1> <p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p> ``` You’ll see the immediate result in the browser:  The routing system has other files we will review in the next chapter, like server-side code for the page component and nested layouts. In the same image, you can see that inside `src` there are two other files: - `app.html` - the entry point of the application - `app.d.ts` - holds global type definitions. ## Reusable Components Now, you are off to the races to develop your SvelteKit application. The simplicity of Svelte makes creating new pages (`+page.svelte` files) a breeze and feels like HTML. If you want to create reusable components, you can do it directly in the route folder. Those files will not be considered pages since they are not part of the naming convention and don’t use the `+` prefix. Speaking of conventions, it’s common in the SvelteKit world to hold the shareable components and utilities inside the `$lib` folder. This `$lib` is a simple alias offered by SvelteKit that points to `src/lib` folder allowing you to import your code easily. Imagine you create a common title component, and create the file under `src/lib/components/Title.svelte` now you want to import that into `+page.svelte`, you will do it like the following snippet. ```html <script> import Title from '$lib/components/Title'; </script> <Title>This is the Title</Title> ``` ## Conclusion In essence, **SvelteKit** is a dynamic and feature-rich framework that's ideal for building modern web applications. Its intuitive syntax, component-based approach, built-in routing, and server-side rendering make it an excellent option for your upcoming web projects. The next step in this journey will be to dive deep into the routing system to start building the todo application! <ResourceWidget resource="next-up" /> <EmailSubscribeWidget /> <ResourceWidget resource="learn-more-svelte" />
article
You already know that in order to get more reliability and safety in your codebase you can use Typescript, but even with it there is room for improvement! One concept that can increase that reliability is **Branded Types**. They provide a way to create deeper specificity and uniqueness for modeling your data beyond that basic types primitives. In this article we’ll explore what branded types are, how to used, some use cases for them and a challenge to ensure the learnings. ## The Problem Typescript helps to ensure that the correct data is passed through your application flow, but more than often, the data is not specific enough. Let’s imagine the following scenario: an application where the users are owners of several other data structure ```tsx type User = { id: string name: string } type Post = { id: string ownerId: string; comments: Comments[] } type Comments = { id: string timestamp: string body: string authorId: string } ``` This define the relation between a `User` type and the `Post` where a `Post` can have many `Comments` that are written by a `User`. The problem here is that the property that identifies each object: `User["id"]`, `Post["id"]` and `Comments["id"]` are actually just `strings` therefore, there is no way for Typescript to catch if your are passing the wrong data, for Typescript, they are all the same and interchangeable. ```tsx async function getCommentsForPost(postId: string, authorId: string) { const response = await api.get(`/author/${authorId}/posts/${postId}/comments`) return response.data } const comments = await getCommentsForPost(user.id,post.id) // This is ok for Typescript ``` The above snippet shows a function that receives two arguments `postId` and `authorId` both of them are just `strings.` But there is an error here, did you catch it?. When calling the `getCommentsForPost` function I passed the arguments in the wrong order, but for Typescript is all the same, so no error. That function call will have the wrong response on runtime, but how can you allow Typescript to catch this errors? We need a way to specify the different types of ID. ## Branded Types? A pattern evolved from the community that is commonly used for this case are **Branded Types**. The idea is to create a more specific and unique data type with greater clarity and specificity, this is accomplished by adding attributes or labels to an existing type to create a new, more specific type. Brands can be added to a type using a union of the base type and an object literal with a branded property. For example: ```tsx type Brand<K, T> = K & { __brand: T } type UserID = Brand<string, "UserId"> type PostID = Brand<string, "PostId"> ``` This creates a new type called `UserID`, which is associated with the `UserId` brand. An actual variable prefixed with this brand type must match the specific type to be used, let’s rewrite the previous example using the new `Brand` helper ```tsx type UserID = Brand<string, "UserId"> type PostID = Brand<string, "PostId"> type CommentID = Brand<string, "CommentId"> type User = { id: UserID; name: string } type Post = { id: PostID; ownerId: string; comments: Comments[] } type Comments = { id: CommentID timestamp: string body: string authorId: UserID } async function getCommentsForPost(postId: PostID, authorId: UserID) { const response = await api.get(`/author/${authorId}/posts/${postId}/comments`) return response.data } const comments = await getCommentsForPost(user.id,post.id) // ❌ This fails since `user.id` is of type UserID and no PostID as expected // ^Argument of type 'UserID' is not assignable to parameter of type 'PostID'. // Type 'UserID' is not assignable to type '{ __brand: "PostId"; }'. // Types of property '__brand' are incompatible. // Type '"UserId"' is not assignable to type '"PostId"'. ``` Check this example in the [Typescript playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAQgTgQwHYBMA8BpANFAKgPigF4oMoAyKAbygH1aAjRVALjygF8AoUSKAVQDOEOAEkAIsVjN0g4HACWSAOY4AREJGiUa-D3DQACgHs5EqfGSz5S1VDUmzOvb2gBhYwFtPEJMHMklqhocooq6h7evv7O+nyacFJUXFBQCihsCRIA3ClQSAg+bKG2XNxxRqbASXnpbI7+4rmpxgDuSFoZUCUqzVAAxl4+foJskcPAggDaALplXBVQ49GCNal1S0PREnnACj5yhWDFNip5DMYoICdhynkIAK7AABbGYl1Z4vNcCIIgSP0oAAzB4AvbGJBQZQQYDLEYAMTeDQAFGAqtp6ujxDhHi83hiBMIxOIAJTUPIAegpwJh-We3S80BQCGACHmgyQcigDyJSQ4UF+hJEUC4HK5aK5JCo-MFDVFEK5gyiIyk0NhWwRSKqyJ5IgAdOksBLgAaUGSqVBADLkeGeClWQIQCgANqtBEp+tAAAa6uCmz1pVbGIFQVxC4kC1D5YxQBrmQUQAAekH6wAgKCAA) This is a good solution to the current problem, but is has some issues or downsides: - the `__brand` property used to “tag” the type is a “build-time” only property. - The `__brand` property is still shown through Intellisense, this can trigger issues if some developer try to use it, since it will not be present on runtime. - Is possible to duplicate branded types since there are no securities on `__brand` property. ## A better Branded Type The previous implementation is a naive interpretation of a branded type. To avoid the listed downside you should use a stronger implementation of the `Brand` utility type. - Instead of using a `hard-coded` property named `__brand` you can use a computed property key. - To avoid duplication of the mentioned `key` you can use a `unique symbol` - Also, write the `Brand` utility into its own file to prevent read access to the property. ```tsx declare const __brand: unique symbol type Brand<B> = { [__brand]: B } export type Branded<T, B> = T & Brand<B> ``` check [this playground link](https://www.typescriptlang.org/play?ssl=7&ssc=40&pln=1&pc=1#code/CYUwxgNghgTiAEYD2A7AzgF3gfWwIxihWAC54BXFASwEdyE0BPAWzyQgCgNGAHBAIULEAPPwB88ALzwA3vADauAkWABdMv3gBfDhxAAPHkhhZufeIJUhgwgCoAaCxOm34AMgtCb43V14IAVTQQGABJABEpTysbTBgqFABzRwAiIJDQ4BSxP3MABSRMCKjLYmthOITk+BSCoqycswQAYSRmZhAUDGLpUtBYjHik1Nb2zu6G3MDgmCiZDnh4KlJ4dLDwgG4F+BQoDrJKpI4dKfg6rGl5xeWyc4itxaQAdxQMlcPEh8Q2jq60MlGvwwaHkqmOuia8EB4zQc22NyhP3GEW2GCoHUwex4B0GVW2bGAjBxQ0S2yg5AwAAtjJkyGsUScoEwUGB4AAzShgNGoeCJEAYaF-ABixnOAAojPVboVuuFHOSqTSVvTwgBKWTbAD0mvZ-LAlPgaDaCGAUAwUHByHQWHIMzmWngTNWdo4Vsw8ElF1kDqd51dqHdyDGfyifIFSOFoplYttIQAdMt7J6E8B1dr4IAZcngtkpVFhbKgVAgsLQCTACAABrGYCmK0tYUg2fBISrHcQdkgzjLik6DHwudYgA) [](https://www.typescriptlang.org/play?#code/C4TwDgpgBAQgTgQwHYBMA8BpANFAKgPigF4oMoAyKAbygH1aAjRVALjygF8AoUSKAVQDOEOAEkAIsVjN0g4HACWSAOY4AREJGiUa-D3DQACgHs5EqfGSz5S1VDUmzOvb2gBhYwFtPEJMHMklqhocooq6h7evv7O+nyacFJUXFBQCihsCRIA3ClQSAg+bKG2XNxxRqbASXnpbI7+4rmpxgDuSFoZUCUqzVAAxl4+foJskcPAggDaALplXBVQ49GCNal1S0PREnnACj5yhWDFNip5DMYoICdhynkIAK7AABbGYl1Z4vNcCIIgSP0oAAzB4AvbGJBQZQQYDLEYAMTeDQAFGAqtp6ujxDhHi83hiBMIxOIAJTUPIAegpwJh-We3S80BQCGACHmgyQcigDyJSQ4UF+hJEUC4HK5aK5JCo-MFDVFEK5gyiIyk0NhWwRSKqyJ5IgAdOksBLgAaUGSqVBADLkeGeClWQIQCgANqtBEp+tAAAa6uCmz1pVbGIFQVxC4kC1D5YxQBrmQUQAAekH6wAgKCAA)to see how this work ## Why are Branded Types useful? Branded types can bring several benefits over using primitive types, such as: - Clarity: It offers a more expressive and clarity about the intended use of the variables. For example, a "Username" branded type can ensure that the variable contains only valid usernames, avoiding issues related to invalid characters or lengths. - Safety and correctness: They can help prevent issues by making it easier to reason about the code and catch errors related to type incompatibility or mismatch. - Maintainability: They can make codebases more maintainable by reducing ambiguity and confusion and thereby making it easier for others to understand the code. By using branded types, developers can communicate their intent more clearly and avoid misunderstandings or misuses of variables. Additionally, branded types can make refactoring easier by providing a clear distinction between different types of data and their respective uses. ## Use Cases Branded types can be used in many scenarios. Here are a few examples: ### Custom validation They can help with the creation of validation functions to ensure that data from the user comports to a standard or desired format. For instance, brands could be used to validate email addresses as being in a proper format: ```tsx type EmailAddress = Brand<string, "EmailAddress"> function validEmail(email: string): EmailAddress { // email address validation logic here return email as EmailAddres; } ``` If at any point in time the email is not of the proper brand or the input is unclear, the user will receive a failure message. ### Domain modeling Branded types excel in domains modeling that can be translated into a more expressive coding experience overall. For instance, a car manufacturing line could use branded types for different features or kinds of cars: ```tsx type CarBrand = Brand<string, "CarBrand"> type EngineType = Brand<string, "EngineType"> type CarModel = Brand<string, "CarModel"> type CarColor = Brand<string, "CarColor"> ``` With this approach, the type checker can now enforce better type safety: ```tsx function createCar(carBrand: CarBrand, carModel: CarModel, engineType: EngineType, color: CarColor): Car { // ... } const car = createCar("Toyota", "Corolla", "Diesel", "Red") // Error: // "Diesel" is not of type "EngineType" ``` ### APIs responses and Requests API endpoints can use brands to help customize the responses and requests from API calls. Branded or labeled types work well in this context because the labeling comes from the API providers. In a hypothetical code example, here, we will use a brand with a specific API to differentiate between successful and failed API calls: ```tsx type ApiSuccess<T> = T & { __apiSuccessBrand: true } type ApiFailure = { code: number; message: string; error: Error; } & { __apiFailureBrand: true }; type ApiResponse<T> = ApiSuccess<T> | ApiFailure; ``` Now you can use this response type, avoiding misconceptions: ```tsx const response: ApiResponse<string> = await fetchSomeEndpoint(); if (isApiSuccess(response)) { // handle success response } if (isApiFailure(response)) { // log error message } ``` ## A Challenge for you The best way to learn something related to code is to actually building or solving something related to the topic. Your task is to create a new branded type for a person's age, a function `createAge` which takes a number input and returns it as `Age` and a function named `getBirthYear` that accepts an `Age` and return a number. `Age` is not just any number, it should belong to the interval \[0, 125\] (inclusive). If the input does not belong to this interval, the function `createAge` should throw an error indicating that the input is not within the valid range. ```tsx /** You can work on this challenge directly in the typescript playground: https://tsplay.dev/WzxBRN*/ /** For this challenge you need to create the Branded utility type */ type Age = Branded<never, "Age">; // Replace the never with the corresponding primitive type /** * 🏋️♀️ Fill the function createAge, it should accept a number as input and return a branded Age **/ function createAge() { // Perform logic and return Age } /** * 🏋️♀️ This function should accept a branded Age type and return a number */ function getBirthYear() { // Perform logic and return Age } /** Usage **/ const myAge = createAge(36); // Should be ok const birthYear = getBirthYear(myAge) // Should be ok const birthYear2 = getBirthYear(36) // This should show an error /** Type Tests */ import type { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<typeof myAge, Age>>, Expect<Equal<typeof birthYear, number>>, Expect<Equal<Parameters<typeof createAge>, [number] >>, Expect<Equal<Parameters<typeof getBirthYear>, [Age] >> ] ``` You can find the solution in [this playground link](https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEYD2A7AzgF3gfWwIxihWAC54BXFASwEdyE0BPAWzyQgCgNGAHBAIULEAPPwB88ALzwA3vADauAkWABdMv3gBfDiAAePJDCzc+8QSpDBhAFQA05idJvwAZOaHXxHDgHoAVP4c8P4elsDwpggAZkbwUPB8MGioAORo8QDmIA5oABZI5BAReCAQqJmRSJF5CFQoGCAwAG5QEAoADA4AjABMAKyq8AAU9ZDkaFTNIACUwYG+XLwIAILZUmHEVsIo5KxNDgBEayCHYgDcPgFBIfAAam1UwFCNGRi18PU85Fi7+zDxDIJVoQJ5ZHI1GBIADuQJQ8CaUIBVGinywVAyKCQGAAdPN-ItopQwBgqKhEHAXiATqMUN8MGQ-qUYDMyCdZMFPqjafT4MJ4B14AAfIWfOk-eASPr9GYc+DyyEw+AoEDQ+AAURgSOGhwAkuKsCD6PBYgD2Rjldj4NCqO96jUECCwUJsoc5vKdJy4BhyDB4V8JVAMidLp6iSgSWT4dkMPwqMY8gBNECwYZQbJs7KymSc+Xe33w4YqtUAESpwxmMxxMYAYkUIMnU7KALTgjie67wACqaHTCAWPg4yHQWGYjBOmYQ0jAlMaNIAzAA2GbneC+XyRGD0IeoTDwPDx96NgHSGNxhPH4Zjk6ynzDvcHi8pmC9DZnw9J5-DJeytcbmx5Ba+SFMU8DAWqRAIlqRiDp2NjLPANggJgGQEhwVDMIYxiRAhcjqnQbQOOqBjgFgWgmlCzDwKkAACUTNmAeRtBAIAoNkaC+D8VAQGgqQ+FEiBBshGzyLmGokSSwj4eQbTCFESCote2QOCcYhiHYYnEXwknSbJ8moo+R7Pg4TJNGpGkKuJ2kYFJBEQMIAAKsBQMwICNMkcnLApFIpnO2TqQopkwEM5maRJNm6fZTmEK57loJ5fDee+T6wAF8gnCFYgcKoQA) ## Conclusion Branded types are powerful features of TypeScript that can help enhance the type safety, maintainability, and clarity of code. They can provide better control over the shape of data, offer more expressive types, and enable compile-time safety checks that reduce debugging time and prevent runtime errors. By using branded types judiciously, you can create more efficient, scalable, and safer TypeScript projects.
article
What do you do when you need to check the type of a certain variable or value? The process of knowing the type of a variable is known as **type narrowing**, which is a way to assert the type to act based on the result. By doing this process, you can get a more specific type, allowing you to perform the correct action, and make your code more expressive and less error prone. The type narrowing process can be achieved in three different ways: - Conditional blocks - Type predicate functions - Discriminated unions In this article, we will review how to use each of them and the pros and cons of each approach. Knowing how to narrow your types is an important skill for any TypeScript developer, and you are probably already doing it! Let's dive in and review how to do type narrowing. <Callout> If you'd like to learn more about type narrowing along with many other more advanced TypeScript courses, check out the course [Advanced TypeScript Fundamentals](https://egghead.io/courses/advanced-typescript-fundamentals-579c174f) </Callout> ## Using Conditional Blocks The first approach is to use simple conditional blocks. We’ll use the good ‘ol `if` block. The idea is to review if the variable has a particular property that informs you that the variable belongs to a certain type. By checking the type, you will inform the Typescript type checker to "move" the type from a broader or larger category to a smaller/specific type. This can be achieved in several ways, one of which involves utilizing the `in` operator to check whether a specific property exists within an object: ```typescript type Square = { size: number; } type Circle = { radius: number; } type Shape = Square | Circle; function area(shape: Shape) { if ("size" in shape) { // shape is a Square return shape.size * shape.size; } // shape is a Circle return Math.PI * shape.radius * shape.radius; } ``` The example creates two types, **`Square`** and **`Circle`**, and a union type, **`Shape`**. Then there is a function, **`area`**, that takes a **`Shape`** and returns the area of the shape. The `shape` argument is annotated as `Shape`, meaning that can be any of the two types in the union. To be able to correctly perform the calculation you need to check what type of shape are you using. The first step is then to check the properties of the `shape` to assert if is a `Circle` or `Square`. The function use the **`in`** operator to check if the **`size`** property exists on the **`shape`** object. If it does, you know that **`shape`** is a **`Square`**. If it doesn't, the you know hat **`shape`** is a **`Circle`** and the calculation can be done using the other property. > Another way to accomplish this is to use the `hasOwnProperty` method on the object variable. For simple objects the `in` operator and the `hasOwnProperty` methods are equivalent. The difference lays on that the `in` operator will return `true` for inherited properties, whereas `hasOwnProperty` function will return `false`. But as everything in life, there are tradeoffs that you need to know. Pros: - Are easy to use and don't require any additional setup. This makes them a good option for simple type narrowing scenarios where you only need to check a variable against a few possible types. - Can be used in a wide range of scenarios, from simple type narrowing to more complex type checking scenarios. Cons: - Can be verbose, especially when dealing with large or complex data structures. - May not work in all scenarios. For example, if you needs to make a type assertion based on a property that is not present in all the types being checked, conditional blocks may not be the best tool for the job. Another potential downside of using conditional blocks is that they can introduce additional branching in the code, which can increase the complexity of the codebase. ## Using Type Predicate Functions First, what are **type predicate functions?** A type predicate function is a function that returns a boolean value, but it **has a special type signature**. For example: ```typescript function isSquare(shape: Shape): shape is Square{ return "size" in shape } ``` The `isSquare` function is a simple function that follows the previous example of using a conditional block with the `in` operator, it takes a variable `shape` and returns a boolean indicating if the `shape` variable is or not a `Square`. The part that differentiate this function from others is the special type signature that includes the `shape is Square` syntax. This tells Typescript that the function is a type predicate that narrows down the type of the `shape` argument to `Square`. Or in other words, you're telling TypeScript that any variable that passes through this function and returns `true` can be **safely considered** a `Square` Here it is in action: ```typescript type Square = { size: number; } type Circle = { radius: number; } type Shape = Square | Circle; function isSquare(shape: Shape): shape is Square{ return "size" in shape } function area(shape: Shape) { if (isSquare(shape)) { // shape is a Square return shape.size * shape.size; } // shape is a Circle return Math.PI * shape.radius * shape.radius; } ``` Same as the previous example, you have two types: `Square` and `Circle` but this time you’ll use the type predicate function `isSquare`. The important bit about type narrowing (with any method) is that after the assertion typescript will show you the narrowed type of the variable, if you hover over `shape` after the use of the type predicate function you can see that is annotated as `Square` and not as `Shape`  Pros: - Are flexible and can be used in a wide range of scenarios. - Can be reusable, making them more efficient and easier to maintain. - Can improve code readability by providing descriptive names for type checks. But maybe more important than the good parts, are the bad parts. Cons: - Can introduce additional complexity and potential errors if not used carefully. If the type predicate function is not properly defined or applied, it may lead to type assertions that are incorrect or incomplete. - Can add overhead to the code, especially if they are applied to a large number of variables. - Can be vulnerable to code changes. What do I mean by “vulnerable to code changes” or “errors if not used carefully”? Type predicates are similar to type assertions. **They are a way to tell Typescript that you know more about the code and types than the analyzer**, and this can be true in several scenarios but you need to be careful with this. Here is an example where you, as a developer, can lie to Typescript and everything will “be good”. ```tsx type Square = { size: number; } type Circle = { radius: number; } type Shape = Square | Circle; function isSquare(shape: Shape): shape is Square{ return "radius" in shape // Here is the change } function area(shape: Shape) { if (isSquare(shape)) { // shape is a Square return shape.size * shape.size; } // shape is a Circle return Math.PI * shape.radius * shape.radius; } ``` A subtle change to the previous example. I just changed the condition inside the `isSquare` function, now the type predicate function says that if the `shape` argument has the `radius` property it should be considered a `Square`. But, squares don’t have a radius right? That subtle change can break the application functionality in runtime since it will be not noticed by the type-checker:  You can see that Typescript still thinks that the `shape` object is an `Square` after the condition. And, there is no error accessing the `size` property because TypeScript understands that if the variable is considered as `Square` it should be ok to access `size`. In summary, type predicates are a nice way to describe what you want, and are both expressive and simple. **However, they can be a double-edged sword.** If you are going to use them, be sure to have a good test suite around to avoid these issues. ## Using Discriminated Unions *Discriminated unions* are a way to define a set of related types, each with a unique discriminator property. These types can be combined into a union type that can be used to represent a range of possible values. By using this “discriminator property” you can do secure assumptions about a type. A *discriminator property* is a common property, present in all the types that are part of the union. You then can use that property to “securely” identify the specific type of an object in the union. **The core idea here is that each type that will be part of the union should have a property, with the same name, but different values.** It can be any property that is common to all the types in the union, but it is usually a string or number: ```typescript type Square { kind: "square"; size: number; } type Circle { kind: "circle"; radius: number; } type Triangle { kind: "triangle"; b: number; h: number; } type SomethingElse { kind: "unknown"; size: number; } type Shape = Square | Circle | Triangle | SomethingElse; ``` Similar to the examples of previous section, let’s use the `Square` and `Circle` shapes but add two more types: `Triangle` and `SomethingElse`. Each of the types have a unique property: `kind` with a unique value for each one. Then, same as before, they are combined into a union named `Shape` Now, let’s refactor the `area` function to use the discriminator to perform its tasks: ```typescript function area(shape: Shape) { switch (shape.kind) { case "square": // shape is a Square return shape.size * shape.size; case "circle": // shape is a Circle return Math.PI * shape.radius * shape.radius; case "triangle": // shape is a triangle return (shape.b * shape.h) / 2 default: // shape is unknown or SomethingElse return shape.size } } ``` The `area` function now use a `switch` statement to revise the `kind` property that is present in all the `Shape` constituent (you can also keep using a series of `if` blocks if you want). Depending on the value of the **`kind`** property, you’ll now what type, `Square`, `Circle`, `Triangle` or `SomethingElse` you have and then calculate the area accordingly. Same as before, you can see the TypeScript will correctly annotate the type of `shape` after the type narrowing check:  Check the code [in the typescript playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAygjgVwIYCdoG8BQUoGsCWAdgCYBcUARAM6KoQUDc2UV+AXhOYQgLYBGEFEwC+mTKEhQAwvhQBjADYZmBEuQpzZi+kxwokxfAipdeAoZlEToAFRT4khAOZKoWAJCqylYPccudTHc+U35BXSgAC1DzBihLMWtYAHseCGBIoicAUQUqZU8ibwoEQlxCZIB3QkYg1g4Y8ITxcGgYSKRJAF5YWjQoAB9pLVchuwdnUZS0jKzc-KZMADNSuWB8ZMIoOiQACioOyHJ2zogASjdmKkr8YDlIqH3DiAA6LwusHBw5JHzKGmQaAopGYXygAHpwSxnlB8FRtr1ARBQV80MAECgtgdTi96tAAFTQnF4iLfX7QDQjeggsE4SFEyRwhEyeRKFF6dIYrYAWSQGReAAUAJJQQnYyAvfSGYyihmvKVGKhMdzuH5-Ci+CYBYFBFX08XQJlIKCa-xslXuNFcx4Gl58WW2yIXKEAJl1xAgSyQCAUwBBFv1MKZpXKVS2yRQ03SmWc82RFqtmLluPYyJwomEQA) Let’s check the good and bad parts of using discriminated unions. Pros: - They allow you to make precise assertions based on its discriminator property. - By using a discriminator property is easy to see which type each variable belongs to. - Can be used from simple to complex modeling use cases. Cons: - Can introduce additional complexity to the code, especially when dealing with large or complex data structures. - Can be vulnerable to changes in the code, especially if the discriminator property is changed or removed. - You need to refactor your code/types to introduce them ## Conclusion Type narrowing is an essential process when writing Typescript code. It is a way to be sure that the value you’re using is of the correct type, and by doing so you can still use the tools offered by your editor as a good auto-completion since Typescript will know exactly what type the variable/value is. In this article, we explored three ways to perform type narrowing: conditional blocks, type predicate functions, and discriminated unions. And for each case we reviewed the pros and cons. The key take away I want you to grab is that none of these approaches are perfect and that it depends on your specific needs. - Conditional blocks are a great option for simple scenarios, - Type predicate functions are a good ergonomic and DRY but have a risk of lying to typescript. - Discriminated unions can be useful for scenarios where you need to work with related types that have a common discriminator property. Regardless of which approach you choose, you need to be mindful of why and how to use them to keep improving the type safety of your codebase. Be sure to check the other articles on the Typescript series: - [Learn the key concepts of typescript’s powerful generic and mapped types](https://egghead.io/blog/learn-the-key-concepts-of-typescript-s-powerful-generic-and-mapped-types) - [Typescript’s powerful type inference with Conditional types and String Literals](https://egghead.io/blog/typescript-s-powerful-type-inference-with-conditional-types-and-string-literals) - [An Introduction to Typescript Generics](https://egghead.io/blog/an-introduction-to-typescript-generics)
article
<Course slug="javascript-internationalization-object-b62d898e" /> Personalizing the user experience is becoming more critical every day, even more so if your application or content is consumed by users in different parts of the world who most likely use other languages, date formats, currency, etc. There are multiple solutions to make your content adapt to the location or language of your users. Still, many of these methods have become outdated, complex, or dependent on a particular framework. Javascript also offers an internationalization solution, the **Intl** object. ## What is Internationalization? The concept of internationalization, or i18n, is the process of supporting different languages, and countries in your application. i18n is commonly confused with Localization or even translation, but i18n refers to developing a product, a process focused on supporting different languages and formats based on locality — a common code base. Providing internationalization support is critical for many products but often overlooked. > Localization refers to the generation of a specific product to target a market or region, including translating content and even modifying the interface and terminology. Typically i18n implementation may include: - Development of software that is independent of a specific language or cultural convention. (e.g. display of times and dates) - Use of localization frameworks - Removal of "hard-coded" text in the code - Support for bi-directional languages - Support for different number formats ## The **Intl** object According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/**Intl**), _"The **Intl** object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and the date and time formatting. The **Intl** object provides access to several constructors and functionality common to the internationalization constructors and other language sensitive functions."_ In other words, through the global **Intl** object, you can access a set of tools to work with content sensitive to the user's language. Most browsers currently support these methods well based on information available at [caniuse.com](https://caniuse.com/?search=Internationalization%20API)  TLDR; A quick example of what this API can achieve: ```js const value = 1234.39; const today = new Date("2022-09-07"); /** * @param locale is a string that represents a location code */ function dateFormatter(locale) { const dateFormatter = new Intl.DateTimeFormat(locale) const currencyFormatter = new Intl.NumberFormat(locale, { style: 'currency', currency: 'USD' }) const date = dateFormatter.format(today) const currency = currencyFormatter.format(value) console.log(locale, date, currency); } dateFormatter("en-US"); // expected output: en-US 9/7/2022 $1,234.39 dateFormatter("es-ES"); // expected output: es-ES 7/9/2022 1234,39 US$ ``` You can see a demo of this code in [the following link](https://jsitor.com/BtkNjWJNw) In this code, you can briefly see some methods and transformations that **Intl** can do. - Gives you static access to different constructors, in this case, `DateTimeFormat` and `NumberFormat` - Allows you to "transform" content from one format to another based on the value of `locale` It is essential to note that the `locale` argument is received by all constructors exposed by **Intl**. This `locale` is the value you will ideally capture dynamically so you can modify content based on its value. Browsers offer a method of getting the value of `locale` based on the user's preferences or location. ```js const locale = navigator.language console.log(locale); // "es-CL" ``` ## What is `locale`, and how does it work? When we refer to `locale` we refer to a string that represents a group of user preferences like: - Date and Time - numbers and currency - Time zones, languages, and countries - Measurement units This `locale` string must follow a particular format to be used, this consists of: * A subtag or language code * (optional) a region or country subtag * (optional) a subtag script * (optional) one or more variation subtags * (optional) one or more [BCP-47](https://datatracker.ietf.org/doc/html/rfc4647#section-3.4) extension sequences  Each subtag or sequence used to create the `locale` string is separated by a hyphen. Also, identifiers identify the case. Some examples of `locale` strings * "es": Spanish (language) * "es-CL": Spanish (language) as it is used in Chile (region) * "zh-Hans-CN": Simplified Chinese (language) (script) as used in China (region) When a `locale` string is passed as an argument to one of **Intl**'s provided constructors, it is compared to a list of available `locales` for the best fit. This process is done using one of two possible algorithms: `lookup` or `best-fit`. The `lookup` algorithm checks if the runtime environment has the `locale` used by searching from the most specific to the least detailed result. If the exact value of `locale` is unavailable, it will return the closest one. For example, if you search for `de-DE-u-co-phonebk` if not found, you can return `de-DE`, and in case of not seeing `de` reference will return a default value. The `best-fit` algorithm is an improvement of the previous algorithm where a default value is not returned if the search is not found. If not, the one that best "fits" is returned. IF `es-CL` is searched for but not found, `es-AR` will be returned instead of just `es`. You can learn more about this process by [reviewing the documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/**Intl**#locale_identification_and_negotiation). #### What does each subtag of the string mean? As described above, the string locale is made up of different parts separated by a hyphen, the first section being the language identifier. What are the rest used for? **Script code** This script code is used to identify in what "format" a particular language is written. For example, in Asian languages `Hans` means that Simplified Chinese will be used vs. `Hant`, which indicates that Traditional Chinese will be used. **Variant code** Variant codes represent the different dialect options for a specific language. **Extensions** Extensions include identifiers for different calendars, and numeric or ordering systems. In the example of the previous image, `phonebk` identifies the variant indicating the ordering used for the letters, in this case phone book style. ## Time to code ### Formatting dates and time Let's start by formatting dates and times based on different values of `locale`. For this, you need access to the `DateTimeFormat` constructor. ```js const date = new Date(); //Today's date // Fecha en formato USA const usaDate = new Intl.DateTimeFormat('en-US').format(date) // 9/8/2022 // Fecha en formato Chile const clDate = new Intl.DateTimeFormat('es-CL').format(date) // 08-09-2022 // Fecha en formato Aleman const deDate = new Intl.DateTimeFormat('de').format(date) // 8.9.2022 // Fecha en formato Arabico egipto const arDate = new Intl.DateTimeFormat('ar-eg').format(date) // ٨/٩/٢٠٢٢ ``` Find a demo of this code [in this playground](https://jsitor.com/0XTIZA4QI) This is the basic way to format date and time, but each constructor provided by the **Intl** object accepts a second argument that allows you to modify the result. For `DateTimeFormat` the options are: ```ts type Options = { dateStyle: 'full' | 'long' | 'medium' | 'short', timeStyle: 'full' | 'long' | 'medium' | 'short', calendar: 'buddhist' | 'chinese' | 'coptic' | 'dangi' | 'ethioaa' | 'ethiopic' | 'gregory' | 'hebrew' | 'indian' | 'islamic' | 'islamic-umalqura' | 'islamic-tbla' | 'islamic-civil' | 'islamic-rgsa' | 'iso8601' | 'japanese' | 'persian' | 'roc' | 'islamicc', dayPeriod: 'narrow' | 'short' | 'long', numberingSystem: 'arab' | 'arabext' | 'bali' | 'beng' | 'deva' | 'fullwide' | ' gujr' | 'guru' | 'hanidec' | 'khmr' | ' knda' | 'laoo' | 'latn' | 'limb' | 'mlym' | 'mong' | 'mymr' | 'orya' | 'tamldec' | 'telu' | 'thai' | 'tibt', localeMatcher: 'lookup' | 'best fit', year: "numeric" | "2-digit", month: "numeric" | "2-digit" | "long" | "short" | "narrow", day: "numeric" | "2-digit", hour: "numeric" | "2-digit", minute: "numeric" | "2-digit", second: "numeric" | "2-digit", era: "long" | "short" | "narrow", weekday: "long" | "short" | "narrow", hourCycle: 'h11'|'h12'|'h23'|'h24', hour12: boolean, timeZone: string, formatMatcher: 'basic' |'best fit', timeZoneName: 'long' | 'short' |'shortOffset'|'longOffset'|'shortGeneric'| 'longGeneric' } ``` You have many options to define the best way to display a date and time in your application. Let's review some examples. ```js const options = { year: "2-digit", month: "long", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", weekday: "long", hour12: true, timeZone: 'America/Santiago' } // Date in USA format const usaDate2 = new Intl.DateTimeFormat('en-US', options).format(date) // Thursday, September 8, 22 at 10:20:54 AM const clDate2 = new Intl.DateTimeFormat('es-CL', options).format(date) // jueves, 8 de septiembre de 22, 10:20:54 a. m. // Date in German format const deDate2 = new Intl.DateTimeFormat('de', options).format(date) //Donnerstag, 8. September 22 um 10:20:54 AM // Date in Arabic Egypt format const arDate2 = new Intl.DateTimeFormat('ar-eg', options).format(date) // الخميس، ٨ سبتمبر ٢٢ في ١٠:٢٠:٥٤ ص ``` ### Formatting Numbers Another constructor offered by **Intl** is `NumberFormat`. You can use this constructor to change the way numbers are represented on the screen. The only difference between `DateTimeFormat` and `NumberFormat` constructors is the set of options that these contructors receives. ```ts type Options = { compactDisplay?: "short" | "long"; // Only used when notation is "compact" currencyDisplay?: "symbol" | "narrowSymbol" | "code" | "name"; currencySign?: "standard" | "accounting"; localeMatcher?: "lookup" | "best fit"; notation?: "standard" | "scientific" | "engineering" | "compact"; numberingSystem?: 'arab' | 'arabext' | 'bali' | 'beng' | 'deva' | 'fullwide' | 'gujr' | 'guru' | 'hanidec' | 'khmr' | 'knda' | 'laoo' | 'latn' | 'limb' | 'mlym' | 'mong' | 'mymr' | 'orya' | 'tamldec' | 'telu' | 'thai' | 'tibt'; signDisplay?: "auto" | "always" | "exceptZero" | "negative" | "never" ; style?: "decimal" | "currency" | "percent" | "unit"; unit?: string; unitDisplay?: "long" | "short" | "narrow"; useGrouping?: "always" | "auto" | boolean | "min2"; roundingMode?: "ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | halfEven"; roundingPriority?: "auto" | "morePrecision" | "lessPrecision"; roundingIncrement?: 1 | 2 | 5 | 10 | 20 | 25 | 50 | 100 | 200 | 250 | 500 | 1000 | 2000 | 2500 | 5000; trailingZeroDisplay?: "auto" | "stripIfInteger"; minimumIntegerDigits?: number; minimumFractionDigits?: number; maximumFractionDigits?: number; minimumSignificantDigits?: number; maximumSignificantDigits?: number; } ``` Using this extensive list of options, you can very likely format a number with every possible use case. Check this quick example. ```js function currencyFormatter({ currency, value}) { const formatter = new Intl.NumberFormat('en-US', { style: 'currency', minimumFractionDigits: 2, currency }) return formatter.format(value) } const value = 123456 const dollar = currencyFormatter({ currency: "USD", value }) //$123,456.00 const pound = currencyFormatter({ currency: "GBP", value }) // £123,456.00 const peso = currencyFormatter({ currency: "CLP", value }) // CLP 123,456.00 const dinar = currencyFormatter({ currency: "DZD", value }) // DZD 123,456.00 ``` In this code snippet, you can see the following - A function was created to hold the formatter. - The formatter is always using the `en-US` locale. - Three options define what style of number formatting will use `style: currency`. Even though we kept the same locale, the values returned by the formatting function are different. > What would happen if you also changed the locale for each currency conversion? In case these options don't cover your use-case, you can use another method that is provided by the formatter: `formatToParts`. This method will return an array of objects representing the number as a string in parts so you can use them to customize and solve your particular situation. ```js const formatToParts = new Intl.NumberFormat('en-US', { currency: 'USD', style: 'currency', minimumFractionDigits: 2 }).formatToParts(value) /* [ { type: "currency", value: "$"}, { type: "integer", value: "123" }, { type: "group", value: "," }, { type: "integer", value: "456" }, { type: "decimal", value: "." }, { type: "fraction", value: "00" } ] ``` What if you want to show a number like the social networks? Like `1.2K`? The `NumberFormat` can solve that. ```js // Compact format function formatCompact(value) { const result = new Intl.NumberFormat( 'en-US', { notation: "compact"} ).format(value) return result; } const res1 = formatCompact(123) // 123 const res2 = formatCompact(1234) // 1.2K const res3 = formatCompact(12345) // 12K const res4 = formatCompact(123456) // 123K const res5 = formatCompact(1234567) // 1.2M ``` In this case, the solution involves the use of the `notation` option. You can find a demo for the number formatting [in this playground.](https://jsitor.com/YX91hj0gX) ### Relative Time Sometimes, you want to display the dates in a relative form such as: `2 weeks ago`. You can do this by doing some math and string concatenation with the dates, but *Intl* helps you with this. *Intl* expose a constructor named *RelativeTimeFormat* that, same as before, accepts an argument to tell it what language you want to use and a set of options ```ts type Options = { localeMatches: 'best fit' | 'lookup', numeric: 'always' |'auto' // The format of the output style: 'long' | 'short' | 'narrow' } ``` For this constructor the `format` method accepts a numeric value (*NOT A DATE*) like this ```js const formatter = new Intl.RelativeTimeFormat('en-US'); const monthAgo = formatter.format(-1, 'month') // 1 month ago const futureMonth = formatter.format(1, 'month') // in 1 month ``` When would you use something like this? Imagine a list of articles, each article have a publication date, but you don't want to show just that, you want to show how much relative time is between the publication date and today (the day the user is reading the list). To accomplish this you'll need to do a little math to get the difference between the two dates and use that result as a relative time value. ```js const publicationDate = new Date('2022/01/05') const currentDate = new Date() const msPerDay = 1000 * 60 * 60 * 24; const diffTime = Math.abs(currentDate - publicationDate); const diffDays = Math.ceil(diffTime / msPerDay); const enRtf = new Intl.RelativeTimeFormat("en-US", { numeric: 'auto', }); console.log(enRtf.format(-diffDays, "day")); // 251 days ago console.log(enRtf.format(-diffDays/30, "month")); //8.367 months ago const esRtf = new Intl.RelativeTimeFormat("es-ES", { numeric: 'auto', }); console.log(esRtf.format(-diffDays, "day")); // hace 251 días console.log(esRtf.format(-diffDays / 30, "month")); // hace 8.367 meses ``` Check the demo playground [in this link](https://jsitor.com/P9XZ1ET9L) ### Pluralization The *Intl* object also supports a way to define plural-sensistive content with the *PluralRules* constructor. One use case for this feature is to show the number of items that exist in your collection, ideally this should respect the grammatical numbering in each language you choose to use. You can always get around this requirement by writing your copy avoiding the need of pluralization, but what happen is you need it? Let's check an example ```js function pluralize(locale, count, singular, plural) { const pluralRules = new Intl.PluralRules(locale); const numbering = pluralRules.select(count); switch (numbering) { case 'one': return count + ' ' + singular; case 'other': return count + ' ' + plural; default: throw new Error('Unknown: '+ numberig); } } function showItemsQuantity(count) { return pluralize('en-US', count, 'item', 'items') } const zeroItem = showItemsQuantity(0) // 0 items const oneItem = showItemsQuantity(1) // 1 item const manyItem = showItemsQuantity(12) // 12 items // Spanish function mostrarCantidadCajas(count) { return pluralize('es-ES', count, 'caja', 'cajas') } const ceroItem = mostrarCantidadCajas(0) // 0 cajas const unoItem = mostrarCantidadCajas(1) // 1 caja const muchosItem = mostrarCantidadCajas(12) // 12 cajas ``` Check the demo [in the playground](https://jsitor.com/exTjrc0s_V) > Note: in a real-woprld sceneario, you wouldn't hardcode plurals > in this snippet; they'd be part of your translation files Maybe this example is too naive, since English and Spanish have just two pluralization rules; however, not every language follow this rule, some have only a single plural form, while other have multiple forms. > This example has been borrowed from [v8 blog](https://v8.dev/features/intl-pluralrules) ```js const suffixes = new Map([ ['zero', 'cathod'], ['one', 'gath'], // Note: the `two` form happens to be the same as the `'one'` // form for this word specifically, but that is not true for // all words in Welsh. ['two', 'gath'], ['few', 'cath'], ['many', 'chath'], ['other', 'cath'], ]); const pr = new Intl.PluralRules('cy'); const formatWelshCats = (n) => { const rule = pr.select(n); const suffix = suffixes.get(rule); return `${n} ${suffix}`; }; formatWelshCats(0); // '0 cathod' formatWelshCats(1); // '1 gath' formatWelshCats(1.5); // '1.5 cath' formatWelshCats(2); // '2 gath' formatWelshCats(3); // '3 cath' formatWelshCats(6); // '6 chath' formatWelshCats(42); // '42 cath' ``` This constructor just like the others exposed by *Intl* accepts a second argument to define options. One option is the `type` that allows you to define the selection rule. By default it uses the `cardinal` option. If you want to get the `ordinal` indicator for a number (for example to create a list ) you can accomplish that as follows: ```js const pr = new Intl.PluralRules('en-US',{ type: 'ordinal' }) const suffixes = { one: 'st', two: 'nd', few: 'rd', other: 'th' } const formatOrdinals = n => `${n}${suffixes[pr.select(n)]}` formatOrdinals(0) // 0th formatOrdinals(1) //1sst formatOrdinals(2) // //2nd formatOrdinals(40) //40th formatOrdinals(63) // 63rd formatOrdinals(100) // 100nd ``` ### List Formatting Displaying a list is one of the most used ways to showcase information in a web app. But since your users speaks different language you need a way to format the list based on that language convention. To avoid the hassle of implementing this formatting rules by hand - that could be really hard - *Intl* offers the *ListFormat* API. ```js function getFormatter(locale = 'en-US') { const lf = new Intl.ListFormat(locale); return lf } const enLf = getFormatter() const zfLf = getFormatter('zh') enLf.format(['one']); // One enLf.format(['one', 'two']); // One and two enLf.format(['one', 'two', 'three']); // One, two, and three enLf.format(['one', 'two', 'three', 'four']); // One, two, and three zfLf.format(['one']); // One zfLf.format(['one', 'two']); // One和two zfLf.format(['one', 'two', 'three']); // One、two和three zfLf.format(['one', 'two', 'three', 'four']); // One、two、three和four ``` What this formatter does is basically joining an array of string with the correct conjunction or disjunction to create a meaningful phrase. The default way to format is by using a conjunction unless you pass the `type` options as `disjuntion` ```js const dlf = new Intl.ListFormat('en-US', { type: 'disjunction'}) dlf.format(['One']) // One dlf.format(['One', 'two']) // One or two dlf.format(['One', 'two', 'three']) // One, two, or three dlf.format(['One', 'two', 'three', 'four']) // One, two, three or four ``` As always, you can check the playground [example in this link.](https://jsitor.com/wTiyKccEh) ### Segmentation Segmentation refers to the requirement of splitting some text in segments, for example, split a paragraph in words. The *Intl.Segmenter* constructor offers a locale-sensitive solution to split the text returning meaningful items for the source string. The most naive and most often used solution to split a string is just using `String.prototype.split`, for example splitting a text by whitespaces `.split(' ')`. But, what happen if the language does not use whitespace between words? The result of the split action will be wrong, to avoid this let's use the *Segmenter* constructor. ```js const str = "吾輩は猫である。名前はたぬき。"; const segmenterJa = new Intl.Segmenter('ja-JP', { granularity: 'word' }); const segments = segmenterJa.segment(str); console.table(Array.from(segments)); // [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true}, // etc. // ] ``` Example extracted directly from [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter#basic_usage_and_difference_from_string.prototype.split) ### String comparison The last constructor to review is the *Intl.Collator*, this constructor enables string comparison with locale sensitivity. This constructor is very useful to sort strings that contain extra letters like German or Swedish. Different languages have different sorting rules, let's check a quick example of this ```js const letters = ['ä', 'z'] const listDE = new Intl.Collator('de') const listSV = new Intl.Collator('sv') // in German, ä sorts with a console.log(letters.sort(listDE.compare)); // → a negative value // in Swedish, ä sorts after z console.log(letters.sort(listSV.compare)); // → a positive value ``` Check the code [in the playground](https://jsitor.com/XXRuoOAF1) ## Conclusion Internationalization is an important piece of an application or website that is meant to be used by a worldwide audience, but getting it right is a complex topic. Luckly there are many building blocks directly available from the Javascript engine that can help you implement a locale sensible UI. <Course slug="javascript-internationalization-object-b62d898e" /> That’s a wrap! If you have any questions or feedback, [open an issue on my AMA repo](https://github.com/matiasfha/ama/issues/new/choose) or [ping me on Twitter.](https://twitter.com/matiasfha)
article
As you write more complex types, you'll notice your code growing. You might also start seeing code duplication… When you need to reuse TypeScript code, what do you do? How can you keep your code DRY? How do you reduce the boilerplate code? There are a few main concepts in Typescript that help you accomplish that goal of reducing boilerplate and reusing more code. We’ll be specifically be covering **Generics** and **Mapped Types** Both concepts can be a bit scary at first, mostly because of a knowledge gap that creates a wall and makes the code un-readable at first. **Generics** are a way to create, in the type world, a similar functionality that functions offer. **Mapped Types** are a way to derive and reshape types into new ones. But, before diving into these new concepts, you need to build up your knowledge with the key features that enable the power of Generics and Mapped Types. ## The keyof operator `keyof` is Typescript's answer to JavaScript’s `Object.keys` operator. `Object.keys` returns a list of an object’s keys. `keyof` does something similar but in the typed world only. It will return a literal union type listing the "properties" of an object-like type. This operator is the base building block for advanced typing like mapped and conditional types. > The keyof operator takes an object type and produces a string or numeric literal union of its keys. - Typescript Handbook ```ts type Colors = { primary: '#eee', primaryBorder: '#444', secondary: '#007bff', black: '#000', white: '#fff', whiteBorder: '#f2f2f7', green: '#53C497', darkGreen: '#43A17C', infoGreen: '#23AEB7', pastelLightGreen: '#F3FEFF', } type ColorKeys = keyof Colors; // "primary" | "primaryBorder" | "secondary" .... function SomeComponent({ color }: { color: ColorKeys }) { return "Something" } SomeComponent({ color: "WhateverColor"}) SomeComponent({ color: "primary"}) ``` The code sample above is from a real webapp. The `Colors` type describes a set of colors that can be used across the application. The `keyof` operator retrieves a **literal union** of all the possible colors from the `Colors` type. > **Literal union** means a Union type made up by literal values like "primary" | "primaryBorder" > The union is then used to type the props of `SomeComponent`, allowing the `color` argument to be one of the colors defined in the type. ### `keyof` as constraint The `keyof` operator can also be used to apply constraints to a generic. For this example, it is enough to know that a Generic behaves similarly to a function argument and that the Generic type can have a type or constraint. ```ts function getObjectProps< Obj, Key extends keyof Obj>(obj: Obj, key: Key): Obj[Key] { return obj[key] } ``` The “Generic” code is the odd angle brackets section `<Obj, Key extends keyof Obj>`. That section defines that this function will receive two *"type parameters"* that obey certain rules. Then, the function declares that the arguments are of the type of that *"type parameters"* and it will return a type derived from the generic values as `Obj[Key]` Let's dissect the generic portion of the above function definition: - `Obj` is the name used to identify this Generic parameter. Usually people use single letters to identify the generic, but IMHO it is more clear to use a better name like you would with a variable. The intention here is to accept any object. - The second generic parameter is `Key extends keyof Obj`. Here the `extends` keyword is used as a constraint and can be read as "Key is of ...." meaning that the `Key` generic can only be a value found in `keyof Obj`. - `keyof Obj` is, as mentioned before, a union of string literals from the properties of `Obj` and `Obj` is the first generic parameter. So in Typescript you can reference the previous generic directly. So, does all of that mean? It means that the function arguments of `getObjectProps` will accept any object inside the `obj` argument, but they `key` argument *can only be a string literal that exists as a property of `obj`* ```ts const User = { name: 'Matias', site: 'matiashernandez.dev', location: { country: 'Chile', city: 'Talca' } } const email = getObjectProps(User, 'email') //Argument of type '"email"' is not assignable to parameter of type '"name" | "site" | "location"'. const loc = getObjectProps(User,'location') ``` Other type of constraint that you can write using the `keyof` operator is to restrict the return type of a function. ```ts function objectKeys<Obj extends Record<string, unknown>>(obj: Obj): (keyof Obj)[] { return Object.keys(obj) as (keyof Obj)[]; } ``` The above example can be read as `objectKeys` accepts a `obj` arguments that has to be of type `Record<string, unknown>` and will return an array of all of the properties of that obj. ### `keyof` and template literals. You can also use `keyof` to construct complex template literals like the following example. ```ts type State = { modalOpen: boolean; confirmationDone: boolean; } type SetActions = `set${keyof State}` // setModalOpen | setConfirmationDone ``` This will generate a union of literal strings based on the `State` properties concatenating the property name with the `set` word. As you can see, the `keyof` operator can be small but it is an important piece that unlocks powerful operations when used in the right places. ## The `extends` keyword This keyword is very confusing at first glance. It's used in a few different places with different meanings. The first usage of `extends` is for interface inheritance. This lets you create new interfaces that inherit the behavior of a previous one. In other words, it extends the base interface/class. Interfaces have two main purposes: - Create the contract that a class must implement - Perform type declaration. ```ts interface User { firstName: string; lastName: string; email: string; } interface StaffUser extends User { roles: Array<Role> } ``` The first interface, `User`, describes a type with a few properties representing a general user of a certain application. The second interface, named `StaffUser`, represents a user who is part of the organization and therefore has a set of `roles`. But this user also has `firstName`, `lastName`, and `email`. You don't want to write that over and over again, right? But more important, what if the general `User` entity changes? How can you be sure that the change is represented everywhere else? That's why the `StaffUser` is written with the `extends` keyword, saying that this interface has all of the properties of the `User` interface, plus the ones defined by itself. This usage of `extends` can be used to inherit from multiple interfaces at the same time by using a comma-separated list of the base interfaces. ```ts interface StaffUser extends User, RoleUser { // ... } ``` > This behavior can also be used to extends a Class > Another usage of the `extends` keyword is to **narrow the scope** of a generic to make it more useful. ```ts export type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, > = (context: QueryFunctionContext<TQueryKey>) => T | Promise<T> ``` This usage of `extends` *narrowing down or constraining the type of a generic* is the corner stone to be able to implement conditional types since the `extends` will be used as condition to check if a generic is or not of a certain type. In the example above, from a real world implementation of *tanstack-query*, a new type is defined: `QueryFunction`. This type accepts two generic values, `T` and `TQueryKey`. The `extends` keyword here **constrains** the possible values of the `TQueryKey` generic to be of the type `QueryKey`, defined elsewhere in the source code. In other words, `TQueryKey` has to be of type `QueryKey`. > If you're not yet comfortable with the use of generics, think of them as function arguments in the type world. The `QueryFunction` type can be thought of as a function type that accepts two arguments (generics) named `T`, with a default value of `unknown`, and `TQueryKey`, with a default value of `QueryKey`. > This usage of `extend`, narrowing down or constraining the type of a generic, is the cornerstone of being able to implement conditional types, since `extends` is used as a condition to check whether a generic is or is not of a certain type. ## The `never` keyword. `never` is a type “value” that represents something that will never occur. This is very handy for implementing different types as conditionals and discriminated unions. A simple example can be defining the type of a set of function arguments, where some of those arguments are dependent: ```ts type CardWithDescription = { title?: never; footer?: never; description: string; } type CardWithoutDescription = { title: string; footer: string; description?: never; } type CardProps = CardWithDescription | CardWithoutDescription function Card(props: CardProps) { return null } import React from 'react'; function App() { return ( <> <Card title="Title" footer='footer' /> <Card description='description' /> <Card description='description' title="title" footer="footer" /> // ERROR </> ) } ``` A React component that can accept some props is a good example. In the above code, you can see that there are three types defined: - `CardWithDescription` defines a type that can have a `description` property as `string`, but with `title` and `footer` as `never`, meaning that they cannot be defined or used. - `CardWithoutDescription` is the opposite type, where `description` cannot be used, but `title` and `footer` are mandatory. - `CardProps` defines a union of the previous two which is used to type the props of the `Card` component. With this setup, the `Card` component can only be used with `description` and no `footer` and no `title`, or vice versa. If for some reason you try to use the three props together, you'll get the following error: ``` Type '{ description: string; title: string; footer: string; }' is not assignable to type 'IntrinsicAttributes & CardProps'. Type '{ description: string; title: string; footer: string; }' is not assignable to type 'CardWithoutDescription'. Types of property 'description' are incompatible. Type 'string' is not assignable to type 'undefined'. ``` ## Generics > If you're serious about becoming a true expert and taking your career to the next level, [check out Matt Pocock's Total TypeScript](https://www.totaltypescript.com/) and learn the underlying principles and patterns of being an effective TypeScript engineer. In any programming language you have ways to implement the DRY principle, TypeScript is no different. Generics help you build well-defined and consistent APIs that are also reusable. You can use Generics to build dynamic and reusable pieces of code that resemble JavaScript functions. Let's see an example of a generic in the wild. ```ts type IsArray<T> = T extends any[] ? true : false; type res1 = IsArray<number[]>; type res2 = IsArray<["a", "b", "c"]>; type res3 = IsArray<"this is not an array"> ``` The example shows a type called `isArray`. It receives a Generic "parameter" called `T` and uses that to do some conditional "calculation" to return `true` or `false`. This example can give you a hint: Generics are kind of like the function parameters of the typed world. For convention, the name of the Generics is a single capital letter, but that is not required. You can pass any name to it. ```ts type IsArray<Array> = Array extends any[] ? true : false; ``` To use generics, you need to follow the angle bracket syntax. When Typescript sees angle brackets, it understands that there are type variables defined inside of them. You can pass as many generics as you need. Then, you can use these "type parameters" inside the type definition to the right side of it. Generics can be used all over the place in Typescript. For example, you can use them to create an interface that changes based on the generics used: ```ts interface UserInfo<X,Y> { name: X; rol: Y; } const user: UserInfo<string, number> = { name: "User 1", rol: 1 } const user2: UserInfo<string, string> = { name: "User 2", rol: "admin" } ``` The interface `UserInfo` has two properties that depend on the generics used: · `name` with a type of `X` · `rol` with a type of `Y` So when you use `UserInfo<string, string>`, both properties will be strings. You'll find generics in almost every TypeScript code-base. They're the basic way to create reusable chunks of code and also the basic tool that library authors use to create a flexible API. ## Conclusion Mapped types and generics are powerful tools for any TypeScript developer. With a good understanding of the key features of typescript, such as the `keyof` operator, the `extends` keyword, the `never` keyword, and generics, you can unlock the full potential of TypeScript and write complex solutions for complex data shapes. With these features, you can create and reuse code, narrow down types, and create custom types, all while ensuring that your code remains DRY. For more curated TypeScript content, check out our [TypeScript landing page!](https://egghead.io/q/typescript) <Course slug="up-and-running-with-typescript" />
article
Let's explore how you can use Typescript’s conditional types and template literals to create type algorithms. In the last article, we laid the groundwork by: - creating type annotations for your function arguments and return types - using native utility types to perform type transformations to accommodate your personal requirements - got a handle of Typescript Generics. It's time to go to the next level! By the end, you'll be well on your way to writing your own powerful branching logic on the type-level. Let's get started. ### Why would you want to write algorithms in the type level? Every programming language was built to create solutions by using different algorithms, and Typescript is no different in that regard. The only difference is that the code you write only affects the type level (build time), helping you to check the safety of your code. So, creating type algorithms can help you increase the type safety and accommodate your code to more complex requirements. ### What type of algorithms can you write? The most basic algorithm you can write is code branching. This is, using conditional blocks to allow the data flows to one or other situation based on certain conditions; you know, the old-good `if-else` block. The TypeScript type system is Turing Complete and therefore it also implements code branching strategies, but in a slightly different way. > What does Turing completeness mean? > In general terms: a language or system that is capable of solving any computable problem given enough time and space. Typescript is able to do this, so you can implement solutions to any problem. ## Typescript Conditional Types The code branching strategy in Typescript is known as *Conditional Types* this is, you will define a type whos value depends on some calculation. TypeScript’s *Conditional Types* are what is used for code branching. They are a type whose value is determined by a calculation: ```tsx type ConditionalType = SomeType extends BaseType ? true : false ``` The syntax can be confusing, but it is actually quite similar to a concept you may already be familiar with from the JavaScript world: the [Ternary Operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). The above example can be read as *"If **Condition** then return `true`, return `false` otherwise"*. The **Condition** part is what often trips up newcomers, as it is somewhat strange. Every conditional type uses the `extends` keyword to implement the condition side of the ternary operator. In this case, `SomeType extends BaseType` can be read as *Is `SomeType` assignable to `BaseType`*. We previously discussed the behavior of the `extends` keyword in a previous article in this series, so be sure to review it! > [Learn the Key Concepts of TypeScript’s Powerful Generic and Mapped Types](https://egghead.io/blog/learn-the-key-concepts-of-typescript-s-powerful-generic-and-mapped-types) The type system is actually based on mathematical concepts. You can represent the idea of one type being assignable to another as a concentric circles diagram.  If the type used on the left-hand side of the `extends` keyword "belongs" to or is a "subset" of the type used on the right-hand side, then the condition is deemed `true` and the first branch of the conditional type is returned. Let's create a simple conditional type that will check if a string have the shape of an URL: ```tsx import type { Equal, Expect } from '@type-challenges/utils' const str1 = "<https://matiashernandez.dev>" const str2 = "htpss://not-valid-url" type IsUrl<Url extends string> = Url extends `https://${string}.${string}` ? Url : `${Url} is not a valid URL String` ``` > Check the [Typescript playground](https://www.typescriptlang.org/play?#code/PQKgBAqgLglgNjKBPMUD2YDGAnApgQyl1VwGcpSt9SyRgAoemAWwAc1spUlXiBvMAFEAjgFd8cADRCAHr0xcAvmABm2NMzAByAALJeAWkwALCXFwA7AOZlgo2HFJbG9TGgvkw5bAEYwAXjAAImMoKFZSAC5gYGZCGGpjXGwLfAsAE1wALwA6TIA3INd3T28AJgDg0IiomIs0KAN8iRh0g1FsOCL6fWIASVIIToAeIbgwXBkiDMpvGGsAPkqxianLdMoAA1Dw2uAAEj4560Ucw+OrRU2wAH5ITrBIsE3DseUYSnqufDBmhHTIAAlAAyYAAylBsPMrJtGL0qDRKIEANr0MDo2TyKDDETiODDXpoFReSE+aQDMYEni4Ikk3wLBmSRgYzG4BQ4sQSYYvPiE4nld6fBpgH5-VpA0EQqHWTbkwYjPl0soMhZMgC6jBUogsChg7jArHw2BolJWk2mGzp0IWAAoOnAnhSRmMFgBKMB8RiKRiG424MY27w+d0xMAAeQA0j6jSbOoHIWUQ8AwAAxfDwUhAA) to play around > In this example you can see how the power of conditional types is unleashed when is used in combination with Generics and other Typescript features like string literal manipulation. The above example can be read as the following: - `IsUrl` is a "type function" that accepts a Generic parameter named `Url`. - Condition: Does `Url` "match" (is assignable to ) the described string literal? - The string literal side: The right side of the condition is a string literal "shape" that describes how a URL string looks. Start with `https://` followed by *any* string, then a `dot` followed by *any* string. - If the *Condition* passes then "return" the `Url` - If the *Condition* does not pass, then "return" an error message. This type can be used to check if a string literal matches the format of a URL string, such as in the following example: ```tsx function parseUrl<Url extends string>(url: IsUrl<Url>) { } parseUrl(str1) // OK parseUrl(str2) // Fails: Argument of type '"htpss://not-valid-url"' is not assignable to parameter of type '"htpss://not-valid-url is not a valid URL String"'. ``` Conditional types in Typescript are written using the same syntax as the Javascript ternary operator. This is the only way to use code branching since Typescript's type system programming is a functional implementation, which means code must be written using expressions. So, the ternary operator is the right way to go if you need to implement multiple conditions. However, you can also write nested conditions if you need to. But this can become quite messy: ```tsx type CleanPath<T extends string> = T extends `${infer L}//${infer R}` ? CleanPath<`${CleanPath<L>}/${CleanPath<R>}`> : T extends `${infer L}//` ? `${CleanPath<L>}/` : T extends `//${infer L}` ? `/${CleanPath<L>}` : T ``` The code snippet above comes from [tanstack/router source code](https://github.com/TanStack/router/blob/3d284a6b626229909f44c78f424d5c181364ae23/packages/router-core/src/link.ts). It uses a nested conditional type with inference, template literal pattern matching, and recursion to determine the type of a path string. ## Pattern Matching The previous code sample introduced an utility type called `IsUrl`, which is an advanced use of conditional types that checks if a value matches a certain pattern. This is known as **Pattern Matching**. The concept behind pattern matching comes from computer science and is an integral part of the functional programming paradigm. It's described as *"the act of checking a given sequence of tokens for the presence of the constituents of some pattern."* > [Check out this wikipedia entry to read more about the computer science concept!](https://en.wikipedia.org/wiki/Pattern_matching) We are using this feature to check if a type value *extends* the pattern, in the previous case a string literal pattern. But the pattern can be any type. For example: ``` type IsPost<P> = P extends {title: string; author: Author } ? true : false type t1 = IsPost<{title: "This is the title", author: { name: "Matias"}}> // true type t2 = IsPost<{title: "This is the title"}> // false ``` It is important to note that this is type-level pattern matching, which allows you, in combination with conditional types, to perform code branching based on how the condition is evaluated. For more information, check out the Wikipedia page on the computer science concept. ## Template Literals > This will be a brief overview of template literals since we will need a full-leght article just to describe the full feature. > Another feature used in combination with conditional types are **template literals**. Coming from Javascript programming, I'm sure you are used to using template literals to handle your string needs, like concatenating and interpolating strings and variables. The syntax used here is the same as the one used in runtime code, with backticks and curly braces for interpolation. From the previous demo: ```tsx type Template = `https://${string}.${string}` type IsUrl<Url extends string> = Url extends Template ? Url : `${Url} is not a valid URL String` ``` Here, the `Template` type is the template literal that describes the shape of a string. We are interpolating something that can be strange at first glance since is not a value but the primitive type: `string`. The usage of `${string}` describes **any** string. So, `Template` describes the combination of all possible strings that starts with `https://` and have a dot in the middle. This is really powerful for typing function arguments. You can define a template literal type that describes exactly the shape of string the function requires. ```tsx // This accepts any string as userId function fetchUser(userId: string) { } // This accepts only strings with the correct uuid shape type UUID = `${string}-${string}-${string}-${string}` function fetchUser(userId: UUID) { } ``` > The UUID template literal is a simplification of the real UUID specification. > In the example, the second implementation of `fetchUser` can be considered better since the only type of argument that can be passed are the ones that resemble a `uuid`. ## Type Inference You have now learned how to create a conditional type and combine it with Generics, and template literals. But there is more! You can extract "pieces" of data from the types to be used in your conditional algorithm: ```tsx type ExtractDomain<S> = S extends `https://${string}.${infer Domain}` ? Domain : never const str1 = '<https://matiashernadez.dev>' const str2 = '<https://matiashernandez>' type test1 = ExtractDomain<typeof str1> // 'dev' type test2 = ExtractDomain<typeof str2> // never ``` > Go ahead and [check the playground link](https://www.typescriptlang.org/play?ssl=5&ssc=1&pln=6&pc=39#code/PQKgBAqgLglgNjKBPMUD2YDGAnApgQyl1VwGcpSt9SyRgAoemAWwAc1spUlXiBvMAFEAjgFd8cADRCAHr0xcAvmABm2NMzAByAALJeAWkwALCXFwA7AOZlgo2HFJbGmNBfJhy2AIxgAvNrGUFCspABcwMDMhDDUxrjYFvgAJrgAXgB0qQBuzq7uXF4ATP6BwaERUTFxCUkWqWnO9PrEgjJQ2PgKACIa+DAWADwAygB8pcNguO2WyZQABkEh4ZEAJHxeA1aKGesDKglgvdEDivNgAPxHfQNgYWAWuNmHjM08xJjUZKUA2vRgANk8iggxE4jggy0OS00jaHS6UGO-SGLTQKk8HW8o2xkkYgKBuAUoLEEkGj2e2Fh7U6PRuKPeaIx2CK2NGuIAuowgA) to play around with the implementation > The example above implements a utility type that retrieves or extracts the domain string from a URL. It is very similar to what we previously did with the `IsUrl` example: - The type receives a Generic named `S`. - The condition defined checks if `S` matches with the defined template literal. - The template literal is defined as `https://${string}.${infer Domain}` - If `S` matches with the template then it will "return" `Domain`. Otherwise, it returns `never`. The new part here is the 3rd step. The template literal definition includes the new keyword, `infer`. The `infer` keyword enabled the creation of **inline type variables**. This type variable will hold some data that is assigned by destructuring the type passed in the left side of the `extends`. With `infer` you will create a new Generic that can be named anything you want. Typescript will be in charge to perform the assignation of the type. One caveat of the `infer` keyword is that the generic variable created can only be used in the truthy side of the code branching. Let's see another example: ```tsx type NonEmptyArray<A extends any[]> = A extends [infer First, ...any] ? true : "The array cannot be empty" type test1 = NonEmptyArray<[1]> // true type test2 = NonEmptyArray<[]> // The array cannot be empty ``` > As always, [check the playground here](https://www.typescriptlang.org/play?#code/PQKgBAqgLglgNjKBPMUD2YDGAnApgQyl1VwGcpSt9SyRgAoemAWwAc1spUlXiBvMAFEAjgFd8cADRCAHr0xcAvmABm2NMzAByAALJeAWkwALCXFwA7AOZlgo2HFJbG9fcQByaC4LbIAgtjY+EgAPH5guDJEFgAmlPgWSADaALoAfGAAvGDhkdFxYEkwFiq42GAAYjDY5NIAdA0JSClgAPyo2KLEAFxgAEQAKsbE+IHBVBYWaFwARsS4vkh9Lq48xJjUZFmF9GB7svJQISLicCFQnbjSnt6LAUGhSQCM6Wlpkoz7B7gKx2ISIUGwzAoweEyms3miz61y8PlY-jGj1e73oKUYQA) > This example defines a type that allows you to check that an array is not empty, to do so it use a conditional type plus two other features: - `infer` keyword to extract the first element of the array - and **Variadic Tuples** The type can be read as *If A is assignable to an array that contains at least one element then return `true`. Otherwise, return an error message.* The `infer` keyword is also used to create some of the native utility types like `Parameters` ```tsx type MyParameters<F> = F extends (...args: infer Args) => any ? Args : F type fn1 = (arg1: string, arg2: number) => number type fn2 = (obj: { arg1: number, arg2: boolean}) => boolean type noFn = { arg1: number, arg2: boolean} type t1 = MyParameters<fn1> // [arg1: string, arg2: number] type t2 = MyParameters<fn2> // [obj: {arg1: string, arg2: number}] type t3 = MyParameters<noFn> // {arg1: number, arg2: number} ``` > [Link to playground](https://www.typescriptlang.org/play?#code/PQKgBAqgLglgNjKBPMUD2YDGAnApgQyl1VwGcpSt9SyRgAoemAWwAc1spUlXiBvMAFEAjgFd8cADRCAHr0xcAvmABm2NMzAByAALJeAWkwALCXFwA7AOZlgo2HFJbG9fcQCySAAr5s+ZrhE2KQAPABiAHxgALxgYWC4MkQWACaUABQAdNm+VqQAXGAwFiq42GAAgth5AJQxUfgWKAD8ldWUhWEubqoWAIwxYOm5fYXk2MVW0rkATIUWoswARmV10VELy2VgjD0qFjOD6WhLAFaFAiPziyvY09VzYEtoaOaNimtRz68EFjuuPGIFjQYT+sUu1VGYE2t3uVke3zeFkUu0BVBolFiAG16GA8bJ5FAQiJxHAQlirmBxpM4Y8YWUALrSTw+PwBIKhfZ9CI8ySMfEE3AKYliCTkk7nMB8XEC-GU+nYADcMtlYFmhURv2VAsUTLALN8-kCZU5Bx5ET5KsFwpJYuBoOZ3kN7JNIXtFnN9AZjCAA) > The example re-implements the utility type `Parameters` that takes a Generic `F` and, If `F` is a function, it will then return a tuple with the parameters of the function. ## The demo Let's review a full demo of a utility type that relies on Conditional Types, `infer` keyword and recursion. We’ll build a simple query string parser, that will: - Read a URL string. - Perform some transformations. - Get the query string data as an object type. ```tsx const route = "<https://mysite.com?query=123&user=2&test=some> string" type ExtractQS<R extends string> = R extends `https://${string}?${infer Q}` ? Q : never type _Merge<O,P> = { [K in keyof O | keyof P]: K extends keyof O ? O[K] : K extends keyof P? P[K]: never } type SplitToObject<S extends string, Separator extends string> = S extends `${infer Left}${Separator}${infer Right}` ? Record<`${Left}`, Right> : S type ExtractQSParameters<QS extends string> = QS extends `${infer Var}&${infer Rest}` ? _Merge<SplitToObject<Var,"=">, ExtractQSParameters<Rest>> : SplitToObject<QS,"="> type RouteParameters = ExtractQSParameters<ExtractQS<typeof route>> // { query: "query"; user: "user"; test: "test"; } ``` > Visit [the playground to read more](https://tsplay.dev/w1Akkw) about the implementation > That looks complex right? But at this point we already reviewed all the concepts required to read and understand the snippet: - The first type defined performs a pattern matching task using a simple template literal and extracts the query string part of the URL using `infer Q`. - An internal utility type `_Merge` is then defined that simply takes two object types and merges (and overwrites) their properties into a new object type (using mapped types). - Another helper type is created that will split a string `S` based on a separator `S` using `infer` and pattern matching to return a new Record as key/value pair. - Lastly, it creates a new Conditional Type that takes a query string and, using `infer`, extracts the key/value pair, then merges them into a new object type. This example helps to showcase the power of the type level algorithms that can help you create complex types to handle your data requirements. ## Summary In this article we reviewed one of the most exciting features of typescript, the one that allows you to implement algorithms on the type level. **Pandora's box has been opened for you to implement solutions with your own complex requirements!** - Conditional types are implemented using a ternary operator - Here the `extends` keyword is used to create the condition part of the conditional type. - Conditional types can be used to peform pattern matching. - Conditional types can be used to "extract" type variables using the `infer` keyword. <Course slug="up-and-running-with-typescript" />
article
# Typescript Generics It’s essential for any programmer to write reusable code. Every programming language needs to be able to encapsulate functionality to be shared across the codebase. Typescript is no different in that, but it implements this feature in a slightly different way than your usual runtime language. **TypeScript uses Generics.** Generics are an essential tool for writing reusable and dynamic code in Typescript. They allow you to create components that can be reused across the codebase and work with a variety of types. By leveraging generics, you can apply the DRY principle and create reusable, dynamic code. > In languages like C# and Java, one of the main tools in the toolbox for creating reusable components is *generics*, that is, being able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types. - [Typescript Docs](https://www.typescriptlang.org/docs/handbook/2/generics.html) > In this article, we'll take a closer look at generics, exploring how they work and how to incorporate them into your Typescript code. ## What are Generics? Generics are a pattern that Typescript uses to allow developers to create reusable and dynamic code. It is represented using angle brackets (`<>`). This is used to declare a type argument that is used inside the function signature. For example, the following code shows a simple function that uses generics to define the types of its arguments: ```tsx function toArray<T>(input: T): Array<T> { return [input]; } ``` This function can be read as: "The function `toArray` receives an argument of type `T` and returns an array of that same type `T`." It is common for developers to use single letters to name their generics, although this is not necessary. You can use whatever name you want that makes sense for your code. In the same example you can see a second use of a generic, in this case a **native type helper.** The return type of the function is annotated as `Array`. This is a global or native type offered by Typescript that helps you to define an array of some type. The “some type” part of the sentence is the Generic. In this case, the `Array` helper is using a generic argument named `T`, so this `toArray` function is returning an array of the type passed as the generic. For example: ```tsx toArray(1) // Array<number> toArray({ a: "this is an object"}) // Array<{ a: "this is an object"} > ``` It's worth noting that the `Array` type helper is a generic object that can also be used by its shorthand `[]`, so `Array<number>` is the same as `number[]`. In summary, a Generic is a representation of a type value that is not yet present. You can use the same mental model that you have for a function argument in Javascript. The argument will take a value when the function is called, and the same is true for Generics. ## How can you use generics The first step in your Typescript journey is to learn about the basic types to start annotating your code. After that, you can learn some of the type helpers offered by Typescript, as well as more advanced concepts such as `keyof` and `extends`. > I invite you to read two related articles: [“What are the basic Typescript Types?”](https://matiashernandez.dev/blog/post/typescript-basic-types) on my site and [“Learn the Key Concepts of Typescript's Powerful Generics and Mapped Types”](https://egghead.io/blog/learn-the-key-concepts-of-typescript-s-powerful-generic-and-mapped-types?af=4cexzz) on egghead. > At this point, you are already using generics without even noticing. Most of the Typescript helpers are, in fact, implemented as a generic. Let's review some of them. ## Utility Types Typescript offers a number of utility types that are globally available as part of the language. These are used to perform basic data transformations from one type to another. These types are, in fact, generics, as you'll see in the examples below. ### Partial and Required The first type utility we will explore is `Partial`. Partial is defined as `type Partial<T> = { [P in keyof T]?: T[P] | undefined; }`. This is a generic type that uses another feature called `mapped type`. > Mapped Types are another advanced feature of Typescript that will be covered in a future article. > This type takes a generic named `T` and transforms each property of that object `T` into an optional property, adding the `?` symbol and transforming the value of that property into a union type between the original value and `undefined`. ```tsx type User = { id: string; email: string; age: number } type PartialUser = Partial<User> /* { id?: string | undefined; email?: string | undefined; age?: number | undefined} */ ``` `Required` is the opposite – it takes a generic type (any type) and transforms each of the properties into a required property, that is, it removes the `undefined` part of the union and removes the optional symbol `?`. ### Omit and Pick `Omit` is a utility type that takes two generics and removes properties from that object based on the second argument. ```tsx type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; } ``` The first generic “argument” is named `T` and can be anything you want. The second parameter is named `K` and uses the `extends` keyword as a constraint for the generic. This means that the generic type `K` can only be of a type mentioned in that union. ```tsx type NewUser = Omit<User, "id"> // { id: string; email: string } ``` The opposite utility is `Pick`, which allows you to choose what you want to keep from an object type. ```tsx type NewUser = Pick<User, "string" | "email"> // { id: string; email: string } ``` In this example, both implementations of the `NewUser` type are the same. These are just a few examples of utility types that can transform objects. There are more, and some that are tailored to handle union types. You can check out the [Typescript Playground to get more information](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys) about each one. ## Patterns that use Generics The use of generics falls into some well-known design patterns, such as generic type helpers or type helpers. You can build your own type helpers by, for example, combining utility types. ```tsx type ReadOnlyNewUser = Readonly<Omit<User, "id">> ``` Another way to use generics in your own code is by creating **generic functions**, these are functions that are annotated with a generic, meaning that this function can take a generic type to perform its operations: ```tsx function typedFetch<Data>(url: string): Promise<Data> { return fetch(url).then(res => res.json()) } typedFetch<{ username: string; email: string}>('/someapi/endpoint').then((result) => { console.log(result) }) ``` The example above shows the following: - `typedFetch` receives two arguments, one at the type level and one at the runtime. The type level argument is the generic `<Data>`, which is used to type the return type of the function `: Promise<Data>`. - When `typedFetch` is calls, you are passing a type argument inside the brackets `<{ username: string, email: string}>` that represents the generic value `Data` used in the function declaration. So, `typedFetch` will return a promise with the data passed as generic argument. In this case it will return a Promise of an object with `{username: string; email: string}`. Typescript uses this pattern to define its own functionality. Most of the JavaScript methods are annotated as typed functions, for example: ```tsx const map = new Map() // Map<any, any> ``` The `Map` object is typed as `Map<any, any>`, meaning that to create a `Map` you need to pass two arguments to it, which can accept any type. In fact, the `Map` definition looks like this (comments were stripped out): ```tsx interface Map<K, V> { clear(): void; delete(key: K): boolean; forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; set(key: K, value: V): this; readonly size: number; } ``` This is a generic interface that takes two arguments `K` and `V`, which are used to define the different methods implemented in `Map`. Another good example of generic functions are the React hooks: ```tsx function Component() { const [myState, setMyState] = React.useState<number>(0) function onClick(){ setMyState(n => n +1) } return <button onClick={onClick}>+1</button> } ``` The component is using `useState` to handle a counter state. To get the correct type inference when using `setMyState`, the call to `useState` receives a generic that represents the type of the state that will be stored, in this case `number`. Another reason to use generics is to improve the type inference offered by Typescript. The use of a generic argument when declaring a function helps Typescript to infer the correct types based on the information available: ```tsx function mergeObjects<ObjA, ObjB>(objA: ObjA, objB: ObjB) { return {...objA, ...objB } } const result = mergeObjects({ a: 1, b: "b" }, { n:10, c: [1,2,3] }) ``` Typescript is able to infer the correct type for the `result` variable, showing you that it is the intersection of the generics arguments used: ```tsx const result: { a: number; b: string; } & { n: number; c: number[]; } ``` Here, when calling `mergeObjects` you’re not passing the type arguments, so there is missing information. However, Typescript is "clever enough" to look into the function values or runtime arguments to infer the type arguments. Another important pattern is generic constraints. You should use this pattern most of the time to narrow the scope of the generic argument used. We already mentioned the usage of constraints in the `Omit` utility type definition. When using generics, the default value for the generic argument defined is `unknown`. But, sometimes you need to narrow the scope of that type to be something in particular. For example, the `ReturnType` utility type works on function types. If you pass something else, it will not work as expected. The definition looks like this: ```tsx type ReturnType<T extends (...args: any) => any> = ..... ``` The `T` generic argument is narrowed to be a type that belongs to the right side of `extends`. Here, `extends` is used to check if the generic argument is of a type that satisfies the type defined there. If it is not, Typescript will error, saying that the type does not satisfy the constraint. You can also set default values to the type arguments. Similar to function arguments in pain ol' Javascript, you can define what will be the default value of a generic if the arguments are not passed to the function: ```tsx function createMap<K,V>() { return new Map<K,V>() } const map1 = createMap<number, number>() //Map<number, number> const map2 = createMap<string, number>() //Map<string, number> const map3 = createMap() // Map<unknown, unknown> ``` The function `createMap` takes two type arguments. If they are not passed, the result will be `Map<unknown, unknown>` like the variable `map3`, so there won't be good type inference or autocompletion. To meet the requirement that the `createMap` defaults to `Map<string, string>`, you can use default type values like this: ```tsx function createMap<K = string ,V = string>() { return new Map<K,V>() } const map1 = createMap<number, number>() //Map<number, number> const map2 = createMap<string, number>() //Map<string, number> const map3 = createMap() // Map<string, string> ``` Generics can be used throughout your code, to create dynamic and reusable pieces of code in interfaces, classes, and functions, as shown in the above examples. ## Conclusion Generics are an important piece of Typescript features. They are mostly used by library authors to create really flexible and dynamic code. As an application developer you’ll mostly rely on the type inference provided by TS and the editor, but is worth to learn how to use Generics to solve more complex data requirements. Generics, can look scary at first but with the proper mind set you can leverage its power in a profitable way. <Course slug="up-and-running-with-typescript" />
lessonFree
lessonFree
lessonDuration 4m 54s
Now is time to setup the client to talk with the contract, for that you will need to store and access the contract ABI (this is a file generated by the contract compilation) as well as use ethers to set up a connection to the contract. Once set up is complete, we will listen to any tip events that come in from the contract and display tip information in the application. ## Important SvelteKit is still in beta. Expect bugs! Read more here, and track progress towards 1.0 here. This lesson was recorded before the latest breaking changes, the content is still valid but it sometimes references a file that does not exists anymore. Now: `src/routes/index.svelte` is called `src/routes/+page.svelte` `src/routes/__layout.svelte` is called `src/routes/+layout.svelte` Everything else is 100% valid. This particular content will be updated when Sveltekit reaches 1.0.0 stable.
lessonDuration 4m 11s
Before jumping into the Dapp code you need to setup an Ethereum wallet. There are bunch of wallet applications and types outher, but for this project we're going to use Metamask. ### What is an ethereum Wallet A wallet is an application that let's you interact with your Ethereum account. You're wallet is the one that works as a gate between the Dapp and your data, through it the applications can read your balance, send transactions, etc. You can swap wallet providers at any time or manage multiple accounts in one application. This is because the wallet are non-custodial, meaning that they don't hold your assets, you do. Just to set some concepts down: - An Ethereum account is an "entity" that can send transactions and store some assets, it "lives" inside the blockchain. - The accout have an address (like your profile URL of some social app or your email address) that can be used to send or receive funds. - A wallt is an application that allow you to interact with the Ethereum account. There are different types of Wallets: - Hardware wallets that hold your crypto assets offline - The most secure of all - Mobile apps, like Argent. - Web wallets, that let you interact through the browser: Like Metamask. - Desktp apps
lessonDuration 5m 24s
Tests are important, as always but it may be more important when you are developing an smart contract. Why? Because the blockchain is immutable. The main difference between Solidity development and other languages or environment is that after the implementation of an smart contract in the Ethereum network the contract is immutable, meaning that it will never be modified or updated again. The first code that get's deployed is the one that will remains unchanged for the rest of time. This is because one the main concerns of Solidity is security. If there's a flaw in your contract code, there is no way to patch it later. You would have to tell to the users of the contract to use a different contract (identified by an `address`) to get the fix. Sounds uncomfortable right? But, believe it or not, this is a **feature**. The code that your wrote it becomes a **law**. IF you read the code of an smart contract (and verified that that code is actually the one deployed) you can be sure that every time you call a function it will behave exactly as the code says it. So you need to be sure before deploy and the best way to get that confidence is by testing. [Hardhat](https://hardhat.org/) (the development environment of choice for this course) offers the tools to test the smart contract using Javascript or Typescript by leveraging the power of [Ethers.js](https://docs.ethers.io/) to interact with the Ethereum network and [Waffle](https://getwaffle.io/), a testing library built on top of Ethere.js You already dip your toes on a bit of testing code, now let's add a more robust test to check that the contract behaves as expected.
lessonDuration 1m 21sFree
Numbers have many ways to be displayed on the screen, one of that is to show them in short or compact ways. Instead of an enormous number like `123456`, show `123K`. This and other summarized forms can be easily done by using *Intl.NumberFormat*
lessonDuration 1m 58sFree
Displaying a list is one of the most used ways to showcase information in a web app. But since your users speak different languages you need a way to format the list based on that language convention. To avoid the hassle of implementing these formatting rules by hand - that could be really hard - Intl offers the ListFormat API. What this formatter does is basically join an array of strings with the correct conjunction or disjunction to create a meaningful phrase.
lessonDuration 2m 36sFree
Numbers are another piece of information that have different ways to be formatted based on the different languages that users may use. One example of this is to display a value in different currencies. Currencies have not only different symbols but also different ways to punctuate or accommodate the numbers on them. Javascript offers a way to handle this simply by just defining the language (locale) and the currency symbol you want to use. This API is *Intl.NumberFormat*
lessonDuration 2m 49sFree
When working in an application that will be used or consumed by users all over the world, is important to display the data in a way that makes sense for them. Som data can be simple to change based on their language, like translating text, but what happens with other pieces of information? Dates can be a complex subject. Manually formatting dates based on the language can be bug-prone. Lucky for us, Javascript exposes an API that handles this: *Intl.DateTimeFormat*
lessonDuration 6m
Now that we have an application that is accepting tips to the smart contract that was defined, we need to be able to withdraw the funds that are sent to the contract. The smart contract function for this is already defined so we will just need to call the function from the front end. To do this we will create a new route to display the contract information. We will then check if the current user is the contract owner and if so allow that user to withdraw the contract funds by clicking a button that we wire up to call the withdraw function from the smart contract. ## Important SvelteKit is still in beta. Expect bugs! Read more here, and track progress towards 1.0 here. This lesson was recorded before the latest breaking changes, the content is still valid but it sometimes references a file that does not exists anymore. Now: `src/routes/index.svelte` is called `src/routes/+page.svelte` `src/routes/__layout.svelte` is called `src/routes/+layout.svelte` Everything else is 100% valid. This particular content will be updated when Sveltekit reaches 1.0.0 stable.
lessonDuration 6m 27s
There are several Ethereum test networks like Ropsten, Rinkeby and Kovan that you can use to deploy your contract to have it publicly available without having to use the mainnet and real ETH. In this course you'll deploy to Rinkeby netwok (but, the process is the same for the other networks). The first step will be update your Metamask Wallet to connect to the Rinkeby network. Next, you'll need some test/fake Ethere to use for testing the Dapp in the network, for that you'll need to use a [faucet like this one](https://www.rinkebyfaucet.com/). Just visit that faucet and add your wallet address. You will also deploy your web application to vercel to see your project live on the internet!