惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
月光博客
月光博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Hugging Face - Blog
Hugging Face - Blog
Project Zero
Project Zero
博客园 - 叶小钗
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
L
LINUX DO - 最新话题
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
I
InfoQ
F
Fortinet All Blogs
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
T
Tenable Blog
B
Blog RSS Feed

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
Tidy TypeScript: Prefer union types over enums
2020-11-19 · via oida.dev | TypeScript, Rust

This is the first article in a series of articles where I want to highlight ways on how to keep your TypeScript code neat and tidy. This series is heavily opinionated, so don’t be angry if I ditch a feature that you learned to like. It’s not personal.

Today we look at enums. Enums are a feature that I see used a lot by people who come from languages like Java or C# because they have been so prominent there. Enums are also a feature from “the old days” of TypeScript where the JavaScript landscape was a lot different than it is now. And you can see that, as enums work exceptionally different than any other type in TypeScript.

Enums emit code #

My most preferred way of writing TypeScript is to

  • write regular, modern-day JavaScript.
  • add types wherever we can strengthen TypeScript’s understanding of our code.

This means after a compile step, you end up with the same code as before without the extra type definitions.

Enums, like classes, create both a type and a value. Meaning that e.g. this declaration:

enum Direction {
Up,
Down,
Left,
Right,
}

emits code in the JavaScript output.

var Direction;
(function (Direction) {
Direction[Direction["Up"] = 0] = "Up";
Direction[Direction["Down"] = 1] = "Down";
Direction[Direction["Left"] = 2] = "Left";
Direction[Direction["Right"] = 3] = "Right";
})(Direction || (Direction = {}));

You can get rid of the output if you use a const enum, but too often I’ve seen people using just regular enums everywhere and wondering why their output gets so big. Especially if you put “glue code” between front-end and back-end in enums you can end up with huge files and bundles.

Okay, that’s one thing, and we can handle that by enforcing const enums. But there is also this nasty ambiguity.

Numeric enums are not type-safe #

EDIT: As of TypeScript 5.0, numeric enums have changed drastically. If you encounter things like described below, please update!

Yes, you’ve heard right. Regular numeric enums – as in an enum where you don’t set string values – are not type-safe! If we look back at the Direction enum from earlier a function that takes a direction also takes any number value instead.

enum Direction {
Up,
Down,
Left,
Right,
}

declare function move(direction: Direction): void;

move(30);
// ☝️ This is totally ok! 😱

The reason is that there is a use-case of implementing bitmasks with numeric enums. And people seem to actually do that! Do a quick search for “TypeScript enum bitmask” or “bitwise flags” and see lots of implementations and examples. Enums provide syntactic sugar for this scenario. I’d argue that why this scenario is valid to implement in JavaScript, I’d doubt it’s the most common scenario you would use enums for.

Usually, you want to make sure you only can pass values that are actually valid.

So far for numeric enums. But there’s always string enums, right? They are type-safe, aren’t they? Yes. And they are peculiar!

String enums are named types #

This is still relevant in TypeScript 5.0+.

In a world of structural typings, enums chose to be a named type. This means that even if values are valid and compatible, you can’t pass them to a function or object where you expect a string enum. See this example:

enum Status {
Admin = "Admin",
User = "User",
Moderator = "Moderator",
}

declare function closeThread(threadId: number, status: Status): void;

closeThread(10, "Admin");
// ^ 💥 This is not allowed!

closeThread(10, Status.Admin);
// ^ You have to be explicit!

This is something you can leverage, but it’s also very different from how number enums and the entire rest of TypeScript’s type system work.

Prefer union types #

A simple union type gives you something that works similarly and is much more aligned with TypeScript.

type Status = "Admin" | "User" | "Moderator"

declare function closeThread(threadId: number, status: Status): void;

closeThread(10, "Admin");
// All good 😄

You get all the benefits from enums like proper tooling and type-safety without going the extra round and risking to output code that you don’t want. It also becomes clearer what you need to pass, and where to get the value from. No need to manually map back-end strings to an enum just for the sake of it. Simple, clear, tidy!

If you want to write your code enum-style, with an object and a named identifier, a const object with a Values helper type might just give you the desired behaviour and is much closer to JavaScript (Note that this is not my preferred or recommended way, simple union types are ususally sufficient enough):

const Direction = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const;

// Get to the const values of any object
type Values<T> = T[keyof T];

// Values<typeof Direction> yields 0 | 1 | 2 | 3
declare function move(
direction: Values<typeof Direction>): void;

move(30);
// ^ 💥 This breaks!

move(0);
// ^ 👍 This works!

move(Direction.Left);
// ^ 👍 This also works!

// And now for the Status enum

const Status = {
Admin: "Admin",
User: "User",
Moderator: "Moderator"
} as const;

// Values<typeof Status> yields "Admin" | "User" | "Moderator"
declare function closeThread(
threadId: number,
status: Values<typeof Status>): void;

closeThread(10, "Admin"); // All good!
closeThread(10, Status.User); // enum style

There are also no surprises.

  • You know what code you end up with within the output.
  • You don’t end up with changed behavior because somebody decides to go from a string enum to a numeric enum.
  • You have type-safety where you need it.
  • And you give your colleagues and users the same conveniences that you get with enums.

But to be fair, a simple string union type does just what you need: Type-safety, auto-complete, predictable behavior.

Of course, you can learn and remember all the peculiarities of enums and know quite well how to handle them. But why bother if there is a much clearer and easier way to achieve the same – if not better – type safety entirely in the type system? That’s why I suggest to prefer union types over enums.

Further reading #

Note that as Sergey and Romain point out, refactoring might be more difficult with string unions than with enums.

Related Articles