teleren/devto huggingface dataset:
Don't use TypeScript enum
Tags: javascript, typescript, enums
Published: 2023-12-09 18:46:52

---
title: Don't use TypeScript enum
published: true
date: 2023-12-09 00:00:00 UTC
tags: javascript,typescript,enums
canonical_url: https://goulet.dev/posts/no-typescript-enum/
---

> Trying my hand at a [zero-nuance take](https://chriscoyier.net/2023/10/02/dan-mall-answers-to-common-design-questions/).

## Don't do this

```ts
enum Shape {
  Sphere,
  Rectangle,
  Triangle,
}

const ball = {
  shape: Shape.Sphere,
};
```

## Do this instead

```ts
type Shape = "Sphere" | "Rectangle" | "Triangle";

const ball = {
  shape: "Sphere",
};
```

## Why?

> Seems I'm not good at "zero-nuance", I feel compelled to explain the why behind this take... at least I'll keep it brief.

Enums are not part of the JavaScript language, so the TypeScript compiler generates different runtime code when you use enums. You aren't writing "JavaScript with types" any more. You are writing a different language that transpiles to JS. Don't do that. Keep it simple.

TypeScript is great for type checking as a dev-time benefit: it's additive, you can strip off the types and you still have JavaScript. You can even add types to JavaScript files with JSDoc comments - no need for a build step to strip off types, ship/debug the code you write, even better!

### Related Posts

- [How to Write TypeScript Interfaces in JSDoc Comments](https://goulet.dev/posts/how-to-write-ts-interfaces-in-jsdoc/)
- [Type Guards in Javascript Using JSDoc Comments](https://goulet.dev/posts/type-guard-in-jsdoc/)
Free & Open Source - Capacity Planning & Management Software - For All Tech Admins
Tags: capacity, planning, tracking, forecasting
Published: 2023-12-02 23:22:53

Every Profession has some sort of Resource to manage, be it materials, money, physical or logical resources & with it some vital queries to be answered: At what Rate is my Resource getting consumed? How Long will current stock last? What will be near future requirement?

In Just Two Simple steps of Defining Your Resource & Actively Tracking its Consumption, you can be in total control of your Resource, using a Free & Open Source Software, that is available here: https://sourceforge.net/projects/trcfir/ 

Hope this is useful to all.
Understanding the Vite Project Structure
Published: 2023-12-02 23:15:06

In our previous blog post, we delved into installing React ASAP. As promised, our journey continues into the intricate details of React, spanning from the project structure to hooks, contexts, and ultimately, Redux. Our exploration begins today with an in-depth analysis of the folder structure within a Vite application.

Project Structure Overview:
```
my-app
├── node_modules
├── src
├── .eslintrc.cjs
├── index.html
├── README.md
├── package.json
└── vite.config.js
```

1. `node_modules`:
This directory houses the folders and files of installed dependencies. Notably, these files are omitted from version control (e.g., GitHub). The analogy here is akin to a recipe book; only the description of the required modules is shared, allowing seamless reproduction on other systems using `npm install`.

2. `src`:
The heart of the project resides in the `src` folder. It serves as the workspace where application structure and components are crafted, defining the core functionality of the application.

3. `.eslintrc.cjs`:
The presence of this file signifies the configuration of ESLint, a versatile and customizable linting tool. ESLint aids in maintaining code quality by identifying and reporting on patterns in JavaScript. It acts as a proactive measure, catching issues such as undeclared variables, variable redeclarations, constant value alterations, unnecessary parentheses, and syntactic errors.

### 4. `index.html`:
This file hosts the root element of our application. As the entry point, the application goes to this HTML document during runtime.

### 5. `README.md`:
In the tradition of conventional README files, this markdown document serves to provide a comprehensive description of the project. It facilitates understanding for fellow developers, offering insights into the application's purpose and functionality, thereby minimizing the effort required to comprehend the intricacies independently.

### 6. `package.json`:
Functioning as the recipe book for our project, `package.json` encapsulates essential information. It outlines core dependencies, project scripts, and project specifications, forming a comprehensive guide for the application's structure and behavior.

### 7. `vite.config.js`:
This configuration file plays a pivotal role in shaping the behavior of the Vite development environment. It allows for fine-tuning and customization, providing a tailored development experience to meet specific project requirements.

In subsequent blogs, we will delve deeper into each aspect of this structure, unraveling the intricacies of Vite applications and empowering developers with a profound understanding of each component. Stay tuned for an enlightening journey through React development intricacies.
Simple handy bash script to update your PHP versions in cli and fpm with valet Linux
Tags: php, valet, bash, linux
Published: 2023-12-02 23:09:28

Please consider that this script assumes that you already have php and valet Linux installed.


Just add this to your bash script

```
load_php() {
    version=$1
    case $version in
        7.4)
            sudo update-alternatives --set php /usr/bin/php7.4
            valet use 7.4
            valet restart
            ;;
        8.1)
            sudo update-alternatives --set php /usr/bin/php8.1
            valet use 8.1
            valet restart
            ;;
        8.2)
            sudo update-alternatives --set php /usr/bin/php8.2
            valet use 8.2
            valet restart
            ;;
        *)
            echo "Invalid PHP version: $version"
            ;;
    esac
}

phpvm() {
    if [ "$1" == "use" ]; then
        shift
        load_php "$1"
    else
        echo "Usage: phpvm use <php_version>"
    fi
}
```

Now you can do something like `phpvm use 7.4` and you will get your php version 7.4 set at your cli and at your php-fpm service. 

Credits to [Kenmutesh's post](https://medium.com/@kenmutesh901/run-multiple-php-versions-in-ubuntu-nginx-z-shell-zsh-and-valet-176399a60669)
Top 10 AWS Services You Should Know!
Tags: aws, azure, gcp, cloud
Published: 2023-12-02 22:06:23

**Amazon EC2 (Elastic Compute Cloud)** :- It is a web service that provides resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers.

**Amazon S3 (Simple Storage Services) :-** It is an object storage service that offers industry-leading scalability, data availability, security and performance.

**Amazon RDS (Relational Database Service) :-** It is a fully managed database service that makes it easy to set up, operate, and scale a relational database in the cloud.

**Amazon Lambda :-** It is a serverless compute service that lets you run code in response to events, such as changes to data in an S3 bucket or a database.

**Amazon CloudFront :-** It is a content delivery network (CDN) that securely delivers data, videos, applications, and APIs to customers globally with low latency, high transfer speeds, and no minimum usage commitments.

**Amazon Route 53 :-** It is a scalable domain name system (DNS) that helps developers and businesses route end users to internet applications by translating domain names like www.example.com into IP addresses.

**Amazon SES (Simple Email Service) :-** It is a cost-effective, flexible, and scalable email service that enables businesses and developers to send and receive emails using their own email addresses and domains.

**Amazon SQS (Simple Queue Services) :-** It is a fully managed message queuing service that enables you to decouple and scale microservices, distributed systems, and serverless applications.

**Amazon DynamoDB:-** It is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.

**Amazon SNS (Simple Notification Service ) :-** It is a fully managed messaging service that enables you to decouple and scale microservices, distributed systems, and serverless applications.
Advent of Code #2 (in Crystal)
Tags: crystal, adventofcode
Published: 2023-12-02 21:42:49

Nothing extraordinary about today's problem. Here's a few things I learned about Crystal while solving this one:

- You can define type aliases using `alias` (_shocker_)
- Somewhat unintuitively (to me, at least), you cannot call the `map` method with parentheses. Instead, you wrap the anonymous function in braces (`{}`) and then you can chain methods after that. I think it's idiomatic to leave a space between `map` and the braces, but that means you end up with code that looks like `map {|x| x + 1}.sum`.
- Destructuring arrays works as expected (without the surrounding square brackets), but destructuing hashes isn't really a thing. You can destructure the key/value pair (which is basically an array), or you can destructure the keys or values separately after turning them into arrays.

```crystal
input = File.read("input").strip

alias Games = Hash(Int32, Subsets)
alias Subsets = Array(Subset)
alias Subset = Hash(String, Int32)

games = input.split("\n").reduce(Games.new) do |games, line|
  game, subsets = line.split(":")
  game_number = game[5..].to_i
  subsets = subsets.split(';').map do |subset|
    subset.split(',').reduce(Subset.new) do |set, cubes|
      number, color = cubes.strip.split(' ')
      set.merge({color => number.to_i})
    end
  end
  games.merge({game_number => subsets})
end

bag = {
  "red" => 12,
  "green" => 13,
  "blue" => 14
}

part1 = games.select do |game, subsets|
  subsets.map do |subset|
    subset.map { |color, number| number <= bag[color] }.all?
  end.all?
end.keys.sum

puts part1

part2 = games.values.map do |subsets|
  subsets.reduce do |set, cubes|
    set.merge(cubes) { |_, old, new| Math.max(old, new) }
  end.values.product
end.sum

puts part2
```
How cybercriminals steal your passwords by listening to your keyboard 🕵️‍♀️ 💁‍♀️
Tags: linux, programming, rust, security
Published: 2023-12-02 21:33:06


Cybercriminals often don't have our passwords or tokens after a brute force decryption, but rather simply listen to our keyboard...

In this article, I'll show you how the use of pirated software can steal your passwords with just 10 additional lines of code for GNU/Linux systems.

Let's take a look at this Rust code:

```rust
use std::io::BufRead;

fn main() {
    println!("Enter your token to validate your identity:");
    let mut password: String = String::new();
    //we can hidden the input for more privacy
    let stdin: std::io::Stdin = std::io::stdin();
    stdin.lock().read_line(&mut password).unwrap();
    //send password with HTTPS
}

```

It is a standard function that retrieves a password and then sends it via HTTPS to a server. Without any alteration, this code is 100% secure.

Now, let's assume the user didn't download or compile an authentic version but instead downloaded a version modified by a cybercriminal. We can observe that by using a low-level keyboard handler, not only can they obtain the user's password, but they can also eavesdrop on the entire session.

I will use `k_board` for this.

```bash
cargo add k_board
```

Objectives:

- Obtain password: Listen to the keyboard until an Enter key is pressed.
- Session: Send what is typed to an HTTP server every 10 keystrokes.

```rust
use k_board::{Keyboard, Keys};
use std::io::BufRead;

fn main() {
    println!("Enter your token to validate your identity:");
    let mut password: String = String::new();
    let stdin: std::io::Stdin = std::io::stdin();
    stdin.lock().read_line(&mut password).unwrap();
    // -> send password to the original server
    // -> send password to our server
    // -> Inside logic program: look to every key event
    get_keys_pressed_and_send_it();
}

fn get_keys_pressed_and_send_it() {
    let mut i: u8 = 0;
    loop {
        let key = Keyboard::new().read_key();
        if key != Keys::Null {
            i += 1;
        }
        if i == 10 {
            //send to our server
            i = 0;
        }
    }
}
```

I am a little scared of what cybercriminals can do to me if I use modified software. Advocating for free software is not just about having things "free" in the economic sense of the word, but it is to prevent these kinds of everyday threats.

See you in the next article❣️🤗!!
Money or Passion?
Tags: career, programming, beginners, discuss
Published: 2023-12-02 21:01:39

Although I recognize it may be provocative, this is a genuine question.

What brought you into programming? 

Is it something you always imagined yourself doing, and you would do that anyway, no matter how low the salary would be?

Or is it something you had to do (because you needed money)? Or just a career choice?

Since the current juniors market is flooded (and later mid/senior will also be - that's inevitable), and getting a job will be even harder than it is now, salaries have already started to drop - what are you going to do? 

Will you continue because you love the job, or will you try to switch to something else?

---

If you want to stay anonymous, I started a poll on Reddit (can't open polls here): https://www.reddit.com/r/webdev/comments/189cvy6/money_or_passion/
Growth in the price of the WEBV cryptocurrency token of Web3 Ventures Inc a thousand times: Unlimited potential
Tags: discuss, web3, cryptocurrency, blockchain
Published: 2023-12-02 20:11:55


Cryptocurrencies continue to attract the attention of investors from all over the world, and the [WEBV token of Web3 Ventures Inc](https://w3ven.org
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/do3ekf5iwngows6zfx6x.png)) is no exception. The possibility of price growth a thousand times a year is a delight and surprise, but such a scenario is not impossible in the world of cryptocurrencies.

WEBV is a token developed by Web3 Ventures Inc, a company that deals with blockchain technologies and the creation of decentralized solutions. Their projects and innovative approaches can attract the attention of investors and contribute to the increase in the price of the WEBV token.

In addition, cryptocurrencies in general have a high growth potential. The cryptocurrency market is constantly developing, attracting new participants and investors. Every year more and more people realize the advantages of blockchain technologies and cryptocurrencies, which can contribute to the growth of demand and, accordingly, the price of the WEBV token.

However, it should be remembered that investing in cryptocurrencies involves high risks. The cryptocurrency market is characterized by high volatility, and prices can fluctuate greatly. The influence of external factors, such as regulatory changes or competition from other projects, can also affect the price of the WEBV token.

In 2024, the world may face new challenges and opportunities that may affect the cryptocurrency market. That is why it is impossible to accurately predict the growth of the price of the WEBV token by a thousand times. However, taking into account the growth potential of cryptocurrencies and innovative projects of Web3 Ventures Inc, such a scenario can be implemented.

In conclusion, the increase in the price of the WEBV cryptocurrency token a thousand times in 2024 is an opportunity that cannot be completely excluded. Cryptocurrencies have high growth potential, and Web3 Ventures Inc can be a catalyst for this growth. However, investing in cryptocurrencies always involves risks, and investors are advised to exercise caution and base their decisions on their own research and analysis.
 #AirdropCrypto #Web3 #Blockchain #Trading #Investing #VentureCapital #crypto
Uống Trà Thảo Mộc Herbalife Có Tốt Không
Published: 2023-12-02 20:00:52

Uống trà thảo mộc herbalife có tốt không Tìm hiểu về sản phẩm và lời khuyên cho người dùng
Trà thảo mộc herbalife có nhiều lợi ích cho sức khỏe, đặc biệt là trong việc giảm cân và duy trì cân nặng lý tưởng. Dưới đây là những lợi ích chính của sản phẩm này:

2.1 Giảm cân hiệu quả
Một trong những lợi ích chính của trà thảo mộc herbalife là giúp người dùng giảm cân hiệu quả. Sản phẩm này chứa các thành phần tự nhiên giúp kích thích quá trình trao đổi chất và đốt cháy mỡ thừa trong cơ thể. Đồng thời, việc uống trà thảo mộc herbalife cũng giúp bạn cảm thấy no và giảm cảm giác thèm ăn, giúp kiểm soát lượng calo tiêu thụ hàng ngày.

2.2 Tăng cường sức khỏe
Các thành phần trong trà thảo mộc herbalife cũng có tác dụng tăng cường sức khỏe chung của cơ thể. Chẳng hạn, cây xương rồng có tác dụng giảm cholesterol và hạ đường huyết, lá sen có tác dụng chống viêm và giúp tiêu hóa tốt hơn. Ngoài ra, các loại thảo dược khác trong sản phẩm cũng có tác dụng tăng cường hệ miễn dịch và bảo vệ cơ thể khỏi các bệnh tật.

2.3 Cải thiện chất lượng cuộc sống
Việc duy trì một cân nặng lý tưởng và có một cơ thể khỏe mạnh sẽ giúp bạn có một cuộc sống cân bằng và tốt hơn. Trà thảo mộc herbalife có thể giúp bạn đạt được điều này, đồng thời cũng giúp bạn có thêm năng lượng và sức khỏe để làm việc và vui chơi.
Mời bạn đọc theo dõi các bài viết hay của [FourT-D Shop](https://fourtdshop.com/kien-thuc/uong-tra-thao-moc-herbalife/): "Top 7 loại trà thảo mộc đóng chai nên uống"
6 Tác dụng của trà hoa oải hương mà bạn không thể bỏ qua
Published: 2023-12-02 19:58:15

Giảm căng thẳng và lo âu
Một trong những tác dụng chính của trà hoa oải hương là giúp giảm căng thẳng và lo âu. Hoa oải hương có mùi thơm dịu nhẹ và có tác dụng thư giãn tinh thần, giúp bạn cảm thấy thoải mái và thư thái hơn. Nếu bạn đang gặp phải căng thẳng và lo lắng, hãy thử uống một tách trà hoa oải hương để giúp bạn thư giãn và xua tan những suy nghĩ tiêu cực.

Cách thực hiện
Để tận dụng tối đa tác dụng giảm căng thẳng và lo âu của trà hoa oải hương, bạn có thể làm như sau:

Cho một túi trà hoa oải hương vào một tách nước sôi.
Đợi khoảng 5 phút để trà ngấm đều.
Thêm một ít mật ong để tăng thêm hương vị và tác dụng thư giãn.
Uống trà khi nó còn nóng để cảm nhận được mùi thơm và tác dụng của hoa oải hương.
Ngoài ra, bạn cũng có thể sử dụng trà hoa oải hương trong các buổi tập yoga hoặc khi thực hiện các bài tập thở để giúp thư giãn tinh thần và cơ thể.
Mời bạn đọc theo dõi các bài viết hay của [FourT-D Shop](https://fourtdshop.com/kien-thuc/6-tac-dung-cua-tra-hoa-oai-huong-ma-ban-khong-the-bo-qua/): "Top 7 loại trà thảo mộc đóng chai nên uống"
002 - TSExpert | Readonly Typescript
Tags: typescript, diy, programming, frontend
Published: 2023-12-02 19:43:33

## Wasup, guys...
<br />
<br />

I hope you guys are doing well

Today, one more time we're crafiting other typescript utility for studies purposes. The guy of the moment is the `Readonly` utility.

That built-in utility get a type N and transform all of their properties in readonly properties, creating a safe type without overrides.

Out of the box, typescript already have this utility for production uses. But we'll creating a clone of it today.

Let's see how it works in your default implementation:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58zpbpkenz66ku0i75oj.png)

Alright, let's assume that on this case for some reason, assigning this prop was not allowed, because the admin role is a security level, and cannot be changed manually.

In this case, typescript not helping us, now is the time of `Readonly` utility shine bright.

We can use it, for set all of these properties as readonly property, that is, we're safing lock all properties to never alter.

It looks something like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imy33n65ce05pvdnn6up.png)

In our `Props` type declaration, we wrapped it in `Readonly` default built-in utility and from now on, all props are locked, their are readonly properties.

Instantly we got an error:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24pgfxyguwmwm0hnj93g.png)

And typescript now, dont allow us to override an readonly prop, this is very useful in this and others cases.

<br />
### 🔨 As usual, now we'll create our own implementation of this utility 🔧
<br />

Why?... 

> "What a cannot create, i don't understand" - Feynman R.

## Our own implementation

This utility is very easy to create, the only thing we need to do is create a new object with a *readonly* prefix in each property.

Let's call it, _MyReadonly_, our utility will receive a generic <T>, and override each prop type with readonly, in this way:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1hgs0veg9cqorf8c7h6.png)

Now, works as the built-in utility.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpnn095tbezfug45g843.png)

🤩 That's it for today, folks! 🤩

Follow me for more content about Typescript, Javascript, React and stuffs of these stack content.
Adventofcode 🎄 : Day 2 - JSX
Tags: beginners, codenewbie, softwaredevelopment, react
Published: 2023-12-02 19:38:17

It's December 2nd, so our next quick revision topic is JSX. Let's begin...

**JSX**

JSX is the abbreviation for JavaScript XML. It lets us blend JavaScript with HTML in React. Instead of keeping them in separate files, JSX allows us to write them together, making our code more straightforward and easier to read.  

Using JSX makes our code more organised and easier to manage. It acts like a translator between our JavaScript and the building blocks of our webpage, simplifying how we create and update things in React.

So, when you spot those HTML-like tags in your React code, that's JSX doing its thing, making coding in React more accessible and user-friendly. 

thank you for reading and **KEEP CODING!!!🎄**
Paracetamol.js💊| #221: Explica este código JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2023-12-02 19:36:17

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Intermedio</mark></center>

```js
const fn = () => {
    let x = 20;
    const fn2 = () => {
        let y = 21;
        return x + y
    }
    return fn2;
}

let res = fn();
console.log(res()) // 🤔🤔
```

- A. `20`
- B. `41`
- C. `21`
- D. `undefined`

---

Respuesta en el primer comentario.
Getting Started with Torpe Configuration
Published: 2023-12-02 19:21:09

So, let's create a repo and start the configuration for the Torpe Project.
Firstly, I've created this [repository](https://github.com/kingjotaro/Torpe) for you to follow the code.
After creating the repo, I set up the project boilerplate with NextJS. I chose NextJS because it's easier to deploy on the web with Vercel, nothing more than that.

`npx create-next-app@latest
√ Would you like to use TypeScript? Yes
√ Would you like to use ESLint? Yes
√ Would you like to use Tailwind CSS? Yes
√ Would you like to use `src/` directory? Yes
√ Would you like to use App Router? (recommended) Yes`

After creating the project, we're going to initiate a Git version controller with `git init`. Then, we'll set the upstream using the terminal with `git remote add origin https://github.com/kingjotaro/Torpe`. My first commit will have the message "hello wordo!"

While writing this post, I completely forgot about the CMS webpage, but it's not a big problem. It's common for services to evolve over time. To address this, in the future, I'll migrate both repositories to a monorepo.

The project has been created, and the first commit is done. For this project, I want all commits to follow a pattern. To achieve this, I'll install some dev dependencies to help make my commits more consistent, following this [tutorial](https://dev.to/vitordevsp/padronizacao-de-commit-com-commitlint-husky-e-commitizen-3g1n).