diff --git a/src/site/notes/Bookmarks/Management and Work related/A receipt printer cured my procrastination.md b/src/site/notes/Bookmarks/Management and Work related/A receipt printer cured my procrastination.md new file mode 100644 index 0000000..07d79bb --- /dev/null +++ b/src/site/notes/Bookmarks/Management and Work related/A receipt printer cured my procrastination.md @@ -0,0 +1,205 @@ +--- +{"dg-publish":true,"permalink":"/bookmarks/management-and-work-related/a-receipt-printer-cured-my-procrastination/","tags":["adhd","work","bestpractices","productivity","ideas"]} +--- + + +# [A receipt printer cured my procrastination [ADHD]](https://www.laurieherault.com/articles/a-thermal-receipt-printer-cured-my-procrastination) + +### Why can I focus for hours on a game but procrastinate when writing an email? For over 20 years, I've tried everything to boost my productivity. I've read dozens of books and tested many methods. Nothing made a real difference. But I finally found a solution by understanding what makes video games addictive. And a thermal receipt printer will become the best investment of my life. + +## My fight against procrastination + +I started my business when I was 21 (I'm now 39). I built custom apps and did consulting for accounting software, invoicing systems, and point-of-sale tools. + +Procrastination has always been my biggest struggle. The only way I could get things done was by relying on stress, coming from clients or financial pressure. That worked for a while, but it cost me my health (I burned out) and my business (I went bankrupt). + +I noticed that I have no problem spending hours fully focused on a video game. If I can focus on a game, then my brain must also be capable of focusing on other tasks. So I naturally started asking myself why it's so easy to get hooked by a game, and how I could apply that same effect to tasks I struggle to complete. + +It turns out that many of the struggles I've had throughout my life are linked to ADHD (Attention Deficit Disorder). The goal of this article isn't to focus on ADHD, but it's important to mention. ADHD affects many people, often without them even knowing it, in various ways and at different levels. + +## Why video games hook us + +To understand what makes a video game addictive, let's take first-person shooters (FPS) as an example. FPS games are among the most popular and addictive games. + +An FPS is built around a simple loop: **Aim\*\***→\***\*Shoot\*\***→\***\*Hit** or **Miss**. This is the **game loop**. The outcome, hit or miss, is immediately shown through sounds or visuals. This immediate reaction is called **feedback**. + +For a game to be addictive, the game loop must repeat frequently and give strong feedback. Imagine an FPS where you only meet an enemy every 30 minutes. That wouldn't be engaging. The loop must repeat quickly to keep you interested. + +Feedback in FPS games has improved a lot over time. Early FPS games only showed a simple blood splash when you hit an enemy. Modern games provide much stronger feedback. Now, when you hit an enemy, you might see: + +- the crosshair briefly changes to confirm the hit +- damage numbers pop up above the enemy +- sound effects +- enemy death animations +- a progress bar filling up +- a new skill unlocked +- random reward +- and more... + +Note that a game can have several game loops. For example, there can be another loop for finding random equipment for your character. Feedback can also come from outside the main loop, such as loot boxes or side missions. + +For a game loop to be addictive, other factors matter too. You need to personally enjoy the type of game, and the challenge must match your skill level. If it's too easy or too hard, you won't be hooked. There are dozens of other factors, unique to each player's personality and preferences. + +When all these elements come together, each game loop gives you a small dose of dopamine and creates a state of **flow**. In this state, we're fully focused, we lose track of time, and it's easier to handle complex tasks. + +One final point: Video games are **easy to start**. They require very little motivation or discipline to start playing. + +Key Takeaways: + +- The game loop should repeat often. +- Feedback from the loop should be strong. +- Games are easy to start, even with low motivation. + +## How to apply the feedback loop to our tasks + +Based on what we've just seen, our real-life **game loop** is made up of completing tasks and habits throughout the day. + +Our first goal is to repeat this game loop as many times as possible each day. A simple solution is breaking tasks into smaller parts. Let's take an example everyone can relate to: cleaning the house. At first glance, you might break down "Clean the house" like this: + +- Clean the house + - Clean the kitchen + - Clean the office + - Clean the bedroom + - ... + +If these three tasks take about an hour, that's only three game loops. Another problem is starting a task. Cleaning your bedroom might take 20 minutes, which feels too long when you're not motivated. So you procrastinate. + +My solution is breaking things down even further: + +- Clean the house + + - Kitchen + + - Wash dishes + - Wipe down surfaces + - Clean floor + - Take out trash + + - Bathroom + + - Clean shower + - Clean toilet + - Clean sink and mirror + - Clean floor + + - Bedroom + - Air out the bed + - Make the bed + - Organize closet + - Clean floor + +The rule is simple: the more you procrastinate on a task, the more you should break it down into micro-tasks, even ones that take just 2 to 5 minutes in extreme cases. + +## How to improve feedback + +Now that we have our game loop, we are going to boost the feedback. To do this, I recommend using sticky notes. Write each task on a sticky note. When you finish the task, crumple the note into a ball and throw it into a clear jar. + +This gives us extra feedback: crumpling the paper, the satisfying sound, and seeing our progress in the clear jar. + +One important point: writing your task on a sticky note makes it real. It's no longer just words on a screen. It's harder to procrastinate on something physically in front of you. + +Key Takeaways: + +- Use sticky notes for your tasks. (The task becomes hard to ignore.) +- Once the task is done, crumple the note into a ball. (Feedback) +- Drop your ball into a transparent jar. (Feedback) + +## How to make this easy in practice + +To make this system easy and get your day started, begin with simple, routine tasks. Think about role-playing games. Early levels are easy and help build momentum for the harder levels later. That's why it's important to put your daily habits on sticky notes. Start your day with easy wins. + +For example, the first sticky note waiting for me each morning is to make coffee. When I sit at my computer, my first task is a quick two-minute warmup. I spend one minute typing text in software to measure my typing speed. Then I spend one minute practicing keyboard shortcuts. I do these two tasks every morning without fail. + +Between waking up and starting work, I complete around ten sticky notes with easy, routine habits. This builds momentum and makes it easier to keep working throughout the day. + +I strongly recommend including these morning habits in your sticky note system. It allows you to start the day with quick and easy tasks. If your first task is the hardest of the day, you're more likely to procrastinate. But when you start with your simple morning routine, you gain momentum that makes the rest of your day easier. + +I also make sure to prepare these tasks the night before. This way, I can immediately start working without having to think about creating sticky notes in the morning. + +Key Takeaways: + +- Use sticky notes with your morning routine to start your day strong. +- Begin your workday with quick, easy tasks. +- Prepare your sticky notes the night before, so you can immediately start working in the morning without extra planning. + +## Be flexible! + +My main advice is to stay flexible with this method. I strongly recommend always starting your day with your first tasks and habits on sticky notes. However, this initial momentum might be enough for you to remain productive for the entire day. + +If later in the day you notice you're starting to procrastinate, immediately return to the system. Take a few minutes to refocus, clearly define the next 3 to 5 tasks, write them down on sticky notes, and start working on them right away. Repeat this as many times as necessary. + +Some tasks can't easily be broken into smaller steps. In that case, break them down by time. For example: "Clean for 10 minutes." + +For complex tasks, you might realize your original plan isn't ideal once you begin working. That's fine. You're already in motion, so continue working flexibly, and use your existing sticky notes whenever you feel you've earned feedback. + +You might also have tasks you've procrastinated on for months or even years, causing them to accumulate significantly. For example, maybe your inbox contains thousands of emails. You've probably imagined one day you'll suddenly feel motivated and clear them all at once. That day will never come. Instead, create a daily sticky note that requires you to process all new emails plus a specific number of older emails. It might take months to clear your inbox, but at least you've stopped procrastinating. + +Another scenario that regularly happens to me is planning about ten sticky notes, then completely forgetting about them. I end up doing the tasks but without using the sticky notes for feedback. That's completely fine. In fact, it means I was in a productive flow state, and my objective was accomplished! + +## Get Started! + +I'm sure you've already read dozens of articles and watched countless YouTube videos about productivity, procrastination, and efficiency. Now you absolutely need to take action! No excuses. + +Try this method! No sticky notes? Grab some paper and scissors, and prepare your tasks for tomorrow. Don't have a clear jar? Use a regular glass. For the next few days, use this system and see if it helps. Do you find it easier to complete your tasks? Do you forget fewer important things? + +Keep testing for a few weeks. Think of it like going to the gym. You won't become a bodybuilder with huge muscles after your first workout. Turn this system into a habit! + +Here's why this system works so well: + +- Breaking tasks into small steps allows us to repeat our game loop frequently. +- Starting the day with easy wins builds momentum and makes it easier to continue. +- Crumpling completed tasks and tossing them into a clear jar provides satisfying feedback. +- The clear jar visually highlights progress and strengthens feedback. +- Tasks on sticky notes feel real and tangible. + +## From sticky notes to receipt printer + +Let's be clear. This system works extremely well. It's better than anything else I've tried in my life. And trust me, I've tested many methods that promised to boost productivity. But one big problem remained. It took too long and was painful to write all those sticky notes. Writing only three tasks a day wasn't enough. I needed twenty, thirty, or sometimes even more. On lazy days, I skipped writing notes, and my productivity collapsed. + +One day, I saw a Reddit post about someone using a receipt printer to print daily tasks. I suddenly realized I had the same idea years ago while setting up checkout systems for clients. But, as usual, I procrastinated. + +A receipt printer is perfect for replacing my sticky-note system. I can easily print dozens of habits. These printers are fast, and they automatically cut each ticket. They're also cheap to run. They don't need ink, only paper. A good printer (For example Epson TM-T20III) costs about $150, and each 80-meter roll costs around $3. One roll can print thousands of tasks. + +I created a simple script to print my daily habits. I have a separate list for each weekday because my habits and tasks vary. + +Since the printer can handle a large number of tasks, I added habits and tasks I didn't usually write on sticky notes, making my system even more robust. + +I still use sticky notes for my main work, but much of my daily routine is now managed by my receipt printer. After a few weeks, I noticed something important: I haven't missed a single habit, not even one. + +My productivity had already improved significantly with the sticky-note system. But adding the printer made me truly consistent, boosting my productivity even more. + +Ironically, I previously built a habit-tracking app but always forgot to use it. With this new system, I haven't missed tracking my habits even once. + +Summary of the benefits of the receipt printer: + +- Printing tasks using a receipt printer removes the friction of daily preparation. +- With this system, it will be easy to print more tasks, increasing the system's efficiency. +- Massive reduction in the chances of skipping the system for a day due to procrastination. + +## One more thing + +But there's still one problem. I still waste time writing tasks on sticky notes during the day. My printing script isn't practical. If I want to add habits or new tasks, I have to edit the script manually. That's inconvenient for everyday use, especially when tasks change daily. I needed a simpler solution. + +My first idea was to connect existing software to my printer. But I'm not happy with most existing task apps. They don't easily break down tasks into smaller pieces. Most task apps use a simple, single-level list. Visually splitting tasks into subtasks is impossible. Some task managers offer hierarchical task lists, allowing subtasks. But this creates another problem: the lists become very long and overwhelming. + +A second issue is losing the big picture. Some tasks need breaking down, others don't. This makes task lists messy and hard to manage. + +My third problem is that I need software that's extremely fast to use (ideally keyboard-only for even more speed), so I can create a lot of tasks without feeling frustrated by the UX. + +I spent a lot of time searching for a solution. I tested multiple ideas, wasting countless hours. But I finally found a simple yet brilliant solution. Instead of displaying hierarchical tasks vertically, why not do it horizontally, dividing each level into columns? Each time I click a task, its subtasks appear clearly in the next column. This helps me keep the big picture, filtering tasks I don't need right now. + +You are currently reading the print version of this article. On the web version, you'll find an interactive demo of the concept in this spot. + +Test the concept in this **interactive** demo: + +I built custom software based on this idea and connected it directly to my printer. When I procrastinate, I can quickly break a task into subtasks without messing with my project structure, because subtasks appear in another column. And I can easily print just that column. + +This method, combined with the printer and my app, has changed my life over the past few months. I now have strong, steady productivity, which is a huge daily victory for someone with ADHD. + +Without exaggerating, I believe I've doubled or tripled my productivity. Of course, before this system, I sometimes had very productive days. But I also had many days when I did almost no meaningful work tasks. Those very low productivity days have completely vanished from my life. + +You can watch the video on the web version of this article. + +I truly hope this article inspired you, and that you'll try some of these ideas. + +I plan to release my software publicly in the coming weeks. You can subscribe to my newsletter to get notified when it's available. diff --git a/src/site/notes/Bookmarks/Science and Related/Quantum Zeno Effect.md b/src/site/notes/Bookmarks/Science and Related/Quantum Zeno Effect.md index 2611ff6..705fe52 100644 --- a/src/site/notes/Bookmarks/Science and Related/Quantum Zeno Effect.md +++ b/src/site/notes/Bookmarks/Science and Related/Quantum Zeno Effect.md @@ -31,7 +31,7 @@ The mathematician [Robin Gandy](https://en.wikipedia.org/wiki/Robin_Gandy) recal > [I]t is easy to show using standard theory that if a system starts in an eigenstate of some observable, and measurements are made of that observable _N_ times a second, then, even if the state is not a stationary one, the probability that the system will be in the same state after, say, one second, tends to one as _N_ tends to infinity; that is, that continual observations will prevent motion. Alan and I tackled one or two theoretical physicists with this, and they rather pooh-poohed it by saying that continual observation is not possible. But there is nothing in the standard books (e.g., [Dirac](https://en.wikipedia.org/wiki/Paul_Dirac)'s) to this effect, so that at least the paradox shows up an inadequacy of Quantum Theory as usually presented. > -> —  +> — > > > Quoted by [Andrew Hodges](https://en.wikipedia.org/wiki/Andrew_Hodges) in _Mathematical Logic,_ R. O. Gandy and C. E. M. Yates, eds. (Elsevier, 2001), p. 267. diff --git a/src/site/notes/Bookmarks/Tech/Types vs Interfaces - TypeScript.md b/src/site/notes/Bookmarks/Tech/Types vs Interfaces - TypeScript.md index 5b4ab3c..813fae8 100644 --- a/src/site/notes/Bookmarks/Tech/Types vs Interfaces - TypeScript.md +++ b/src/site/notes/Bookmarks/Tech/Types vs Interfaces - TypeScript.md @@ -1,409 +1 @@ ---- -{"dg-publish":true,"permalink":"/bookmarks/tech/types-vs-interfaces-type-script/","tags":["algorithm","coding","learning","tutorial","work"]} ---- - - -[blog.logrocket.com](https://blog.logrocket.com/types-vs-interfaces-typescript/?ref=dailydev) - -# Types vs. interfaces in TypeScript - LogRocket Blog - -Yan Sun - -17–21 minutes - ---- - -```table-of-contents - -``` - -**Editor’s note:** _This article was last updated on 5 September 2024 by [Vijit Ail](https://blog.logrocket.com/author/vijitail/) to reflect the latest updates on primitive types, union types, and advanced function types in TypeScript_. - -![IMG-20241106232537326.png](/img/user/_resources/IMG-20241106232537326.png) - -We have two options for defining types in TypeScript: types and interfaces. One of the most frequently asked questions about TypeScript is whether we should use interfaces or types. - -The answer to this question, like many programming questions, is that it depends. In some cases, one has a clear advantage over the other, but in many cases, they are interchangeable. - -In this article, I will discuss the key differences and similarities between types and interfaces and explore when it is appropriate to use each one. - -Let’s start with the basics of types and interfaces. - -## Types and type aliases - -`type` is a keyword in TypeScript that we can use to define the shape of data. The basic types in TypeScript include: - -- String -- Boolean -- Number -- Array -- [Tuple](https://blog.logrocket.com/use-cases-named-tuples-typescript/) -- [Enum](https://blog.logrocket.com/typescript-string-enums-guide/) -- Advanced types - -Each has unique features and purposes, allowing developers to choose the appropriate one for their particular use case. - -Type aliases in TypeScript mean “a name for any type.” They provide a way of creating new names for existing types. Type aliases don’t define new types; instead, they provide an alternative name for an existing type. -Type aliases can be created using the `type` keyword, referring to any valid TypeScript type, including primitive types. - -type MyNumber = number; -type User = { -id: number; -name: string; -email: string; -} - -In the above example, we create two type aliases: `MyNumber` and `User`. We can use `MyNumber` as shorthand for a number type and use `User type aliases` to represent the type definition of a user. - -When we say “types versus interfaces,” we refer to “type _aliases_ versus interfaces.” For example, you can create the following aliases: - -type ErrorCode = string | number; -type Answer = string | number; - -The two type aliases above represent alternative names for the same union type: `string | number`. While the underlying type is the same, the different names express different intents, which makes the code more readable. - -## Interfaces in TypeScript - -In TypeScript, an interface defines a contract that an object must adhere to. Below is an example: - -interface Client { -name: string; -address: string; -} - -We can express the same `Client` contract definition using type annotations: - -type Client = { -name: string; -address: string; -}; - -## Differences between types and interfaces - -For the above case, we can use either `type` or `interface`. But there are some scenarios in which using `type` instead of `interface` makes a difference. - -### Primitive types - -Primitive types are inbuilt types in TypeScripts. They include `number`, `string`, `boolean`, `null`, and `undefined` types. -We can use define a type alias for a primitive type as below: - -type Address = string; - -We often combine primitive type with union type to define a type alias, to make the code more readable: - -type NullOrUndefined = null | undefined; - -But, we can’t use an interface to alias a primitive type. The interface can only be used for an object type. -Therefore, when we need to define a primitive type alias, we use `type`. - -### Union types - -Union types allow us to describe values that can be one of several types and create unions of various primitive, literal, or complex types: - -type Transport = 'Bus' | 'Car' | 'Bike' | 'Walk'; - -Union type can only be defined using type. There is no equivalent to a union type in an interface. But, it is possible to create a new union type from two interfaces, like so: - -interface CarBattery { -power: number; -} -interface Engine { -type: string; -} -type HybridCar = Engine | CarBattery; - -### Function types - -In TypeScript, a function type represents a function’s type signature. Using the type alias, we need to specify the parameters and the return type to define a function type: - -type AddFn = (num1: number, num2:number) => number; - -We can also use an interface to represent the function type: - -interface IAdd { -(num1: number, num2:number): number; -} - -Both type and interface similarly define function types, except for a subtle syntax difference of interface using `:` vs. `=>` when using type. Type is preferred in this case because it’s shorter and thus easier to read. - -Another reason to use type for defining a function type is its capabilities that the interface lacks. When the function becomes more complex, we can take advantage of the advanced type features such as conditional types, mapped types, etc. Here’s an example: - -type Car = 'ICE' | 'EV'; -type ChargeEV = (kws: number)=> void; -type FillPetrol = (type: string, liters: number) => void; -type RefillHandler = A extends 'ICE' ? FillPetrol : A extends 'EV' ? ChargeEV : never; -const chargeTesla: RefillHandler<'EV'> = (power) => { -// Implementation for charging electric cars (EV) -}; -const refillToyota: RefillHandler<'ICE'> = (fuelType, amount) => { -// Implementation for refilling internal combustion engine cars (ICE) -}; - -Here, we define a type `RefillHander` with conditional type and union type. It provides a unified function signature for `EV` and `ICE` handlers in a type-safe manner. We can’t achieve the same with the interface as it doesn’t have the equivalent of conditional and union types. - -### Declaration merging - -[Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) is a feature that is exclusive to interfaces. With declaration merging, we can define an interface multiple times, and the TypeScript compiler will automatically merge these definitions into a single interface definition. - -In the following example, the two `Client` interface definitions are merged into one by the TypeScript compiler, and we have two properties when using the `Client` interface: - -interface Client { -name: string; -} - -interface Client { -age: number; -} - -const harry: Client = { -name: 'Harry', -age: 41 -} - -Type aliases can’t be merged in the same way. If you try to define the `Client`type more than once, as in the above example, an error will be thrown: - -![IMG-20241106232537355.png](/img/user/_resources/IMG-20241106232537355.png) - -When used in the right places, declaration merging can be very useful. One common use case for declaration merging is to extend a third-party library’s type definition to fit the needs of a particular project. - -If you need to merge declarations, interfaces are the way to go. - -### Extends vs. intersection - -An interface can extend one or multiple interfaces. Using the `extends`keyword, a new interface can inherit all the properties and methods of an existing interface while also adding new properties. - -For example, we can create a `VIPClient` interface by extending the `Client`interface: - -interface VIPClient extends Client { -benefits: string[] -} - -To achieve a similar result for types, we need to use an intersection operator: - -type VIPClient = Client & {benefits: string[]}; // Client is a type - -You can also extend an interface from a type alias with statically known members: - -type Client = { -name: string; -}; - -interface VIPClient extends Client { -benefits: string[] -} - -The exception is union types. If you try to extend an interface from a union type, you’ll receive the following error: - -type Jobs = 'salary worker' | 'retired'; - -interface MoreJobs extends Jobs { -description: string; -} - -![IMG-20241106232537435.png](/img/user/_resources/IMG-20241106232537435.png) - -This error occurs because the union type is not statically known. The interface definition needs to be statically known at compile time. - -Type aliases can extend interfaces using the intersection, as below: - -interface Client { -name: string; -} -Type VIPClient = Client & { benefits: string[]}; - -In a nutshell, both interfaces and type aliases can be extended. An interface can extend a statically known type alias, while a type alias can extend an interface using an intersection operator. - -### Handling conflicts when extending - -Another difference between types and interfaces is how conflicts are handled when you try to extend from one with the same property name. - -When extending interfaces, the same property key isn’t allowed, as in the example below: - -interface Person { -getPermission: () => string; -} - -interface Staff extends Person { -getPermission: () => string[]; -} - -An error is thrown because a conflict is detected. - -![IMG-20241106232537498.png](/img/user/_resources/IMG-20241106232537498.png) - -Type aliases handle conflicts differently. In the case of a type alias extending another type with the same property key, it will automatically merge all properties instead of throwing errors. - -In the following example, the intersection operator merges the method signature of the two `getPermission` declarations, and a [`typeof` operator](https://blog.logrocket.com/how-to-use-keyof-operator-typescript/) is used to narrow down the union type parameter so that we can get the return value in a type-safe way: - -type Person = { -getPermission: (id: string) => string; -}; - -type Staff = Person & { -getPermission: (id: string[]) => string[]; -}; - -const AdminStaff: Staff = { -getPermission: (id: string | string[]) =>{ -return (typeof id === 'string'? 'admin' : ['admin']) as string[] & string; -} -} - -It is important to note that the type intersection of two properties may produce unexpected results. In the example below, the `name` property for the extended type `Staff` becomes `never`, since it can’t be both `string` and `number` at the same time: - -type Person = { -name: string -}; - -type Staff = person & { -name: number -}; -// error: Type 'string' is not assignable to type 'never'.(2322) -const Harry: Staff = { name: 'Harry' }; - -In summary, interfaces will detect property or method name conflicts at compile time and generate an error, whereas type intersections will merge the properties or methods without throwing errors. Therefore, if we need to overload functions, type aliases should be used. - -### Prefer extends over intersection - -Often, when using an interface, Typescript will generally do a better job displaying the shape of the interface in error messages, tooltips and IDEs. It is also much easier to read, no matter how many types you combine or extend. - -Compare that to the type alias that uses the intersection of two or more types like `type A = B & C;`, and you then type to use that alias in another intersection like `type X = A & D;`, TypeScript can struggle to display the structure of the combined type, making it harder to understand the shape of the type from the error messages. - -Typescript caches the results of the evaluated relationship between interfaces, like whether one interface extends another or if two interfaces are compatible. This approach improves the overall performance when the same relationship is referenced in the future. - -In contrast, when working with intersections, TypeScript does not cache these relationships. Every time a type intersection is used, TypeScript has to re-evaluate the entire intersection which can lead to efficiency concerns. - -For these reasons, it is advisable to use interface extends instead of relying on type intersections. - -### Implementing classes using interfaces or type aliases - -In TypeScript, we can implement a class using either an interface or a type alias: - -interface Person { -name: string; -greet(): void; -} - -class Student implements Person { -name: string; -greet() { -console.log('hello'); -} -} - -type Pet = { -name: string; -run(): void; -}; - -class Cat implements Pet { -name: string; -run() { -console.log('run'); -} -} - -As shown above, both interfaces and type aliases can be used to implement a class similarly; the only difference is that we can’t implement a union type. - -type primaryKey = { key: number; } | { key: string; }; - -// can not implement a union type -class RealKey implements primaryKey { -key = 1 -} - -![IMG-20241106232537548.png](/img/user/_resources/IMG-20241106232537548.png) - -In the above example, the TypeScript compiler throws an error because a class represents a specific data shape, but a union type can be one of several data types. - -### Working with tuple types - -In TypeScript, the tuple type allows us to express an array with a fixed number of elements, where each element has its data type. It can be useful when you need to work with arrays of data with a fixed structure: - -type TeamMember = [name: string, role: string, age: number]; - -Since tuples have a fixed length and each position has a type assigned to it, TypeScript will raise an error if you try to add, remove, or modify elements in a way that violates this structure. - -For example: - -const member: TeamMember = ['Alice', ‘Dev’, 28]; -member[3]; // Error: Tuple type '[string, string, number]' of length '3' has no element at index '3'. - -Interfaces don’t have direct support for tuple types. Although we can create some workarounds like in the example below, it is not as concise or readable as using the tuple type: - -interface ITeamMember extends Array -{ -0: string; 1: string; 2: number -} - -const peter: ITeamMember = ['Harry', 'Dev', 24]; -const Tom: ITeamMember = ['Tom', 30, 'Manager']; //Error: Type 'number' is not assignable to type 'string'. - -Unlike tuples, this interface extends the generic `Array` type, which enables it to have any number of elements beyond the first three. This is because arrays in TypeScript are dynamic, and you can access or assign values to indices beyond the ones explicitly defined in the interface: - -const peter: ITeamMember = [’Peter’, 'Dev', 24]; -console.log(peter[3]); // No error, even though this element is undefined. - -## Advanced type features - -TypeScript provides a wide range of advanced type features that can’t be found in interfaces. Some of the unique features in TypeScript include: - -- Type inferences: Can infer the type of variables and functions based on their usage. This reduces the amount of code and improves readability -- Conditional types: Allow us to create complex type expressions with conditional behaviors that depend on other types -- [Type guards](https://blog.logrocket.com/how-to-use-type-guards-typescript/): Used to write sophisticated control flow based on the type of a variable -- Mapped types: Transforms an existing object type into a new type -- Utility types: A set of out-of-the-box utilities that help to manipulate types - -TypeScript’s typing system constantly evolves with every new release, making it a complex and powerful toolbox. The impressive typing system is one of the main reasons many developers prefer to use TypeScript. - -## When to use types vs. interfaces - -Type aliases and interfaces are similar but have subtle differences, as shown in the previous section. - -While almost all interface features are available in types or have equivalents, one exception is declaration merging. Interfaces should generally be used when declaration merging is necessary, such as extending an existing library or authoring a new one. Additionally, if you prefer the object-oriented inheritance style, using the `extends` keyword with an interface is often more readable than using the intersection with type aliases. - -Interfaces with `extends` enables the compiler to be more performant, compared to type aliases with intersections. - -However, many of the features in types are difficult or impossible to achieve with interfaces. For example, TypeScript provides rich features like conditional types, generic types, type guards, advanced types, and more. You can use them to build a well-constrained type system to make your app strongly typed. The interface can’t achieve this. - -In many cases, they can be used interchangeably depending on personal preference. But, we should use type aliases in the following use cases: - -- To create a new name for a primitive type -- To define a union type, tuple type, function type, or another more complex type -- To overload functions -- To use mapped types, conditional types, type guards, or other advanced type features - -Compared with interfaces, types are more expressive. Many advanced type features are unavailable in interfaces, and those features continue to grow as TypeScript evolves. -Below is an example of the advanced type feature that the interface can’t achieve. - -type Client = { -name: string; -address: string; -} -type Getters = { -[K in keyof T as `get${Capitalize}`]: () => T[K]; -}; -type clientType = Getters; -// type clientType = { -// getName: () => string; -// getAddress: () => string; -// } - -Using mapped type, template literal types, and `keyof` operator, we created a type that automatically generates getter methods for any object type. - -In addition, many developers prefer to use types because they match the functional programming paradigm well. The rich type expression makes it easier to achieve functional composition, immutability, and other functional programming capabilities in a type-safe manner. - -## Conclusion - -In this article, we discussed type aliases and interfaces and their differences. While there are some scenarios in which one is preferred over the other, in most cases, the choice between them boils down to personal preference. -I lean towards using types simply because of the amazing type system. What are your preferences? You are welcome to share your opinions in the comments section below. - -## [LogRocket](https://lp.logrocket.com/blg/typescript-signup): Full visibility into your web and mobile apps - -[![IMG-20241106232537603.png](/img/user/_resources/Bookmarks/Tech/Types%20vs%20Interfaces%20-%20TypeScript/IMG-20241106232537603.png)](https://lp.logrocket.com/blg/typescript-signup) - -[LogRocket](https://lp.logrocket.com/blg/typescript-signup) is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. - -In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps. - -[Try it for free](https://lp.logrocket.com/blg/typescript-signup). +`=>` \ No newline at end of file