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

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

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: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums 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: Name your generics
2021-01-07 · via oida.dev | TypeScript, Rust

My book TypeScript in 50 Lessons features interludes. Short texts on TypeScript culture that provide room to breathe between heavy, technical tutorials. One of those interludes gives some opinionated advice on how to name generic variables.

I want to recap this text piece and elaborate. And this series is called Tidy TypeScript, so expect an even more opinionated stance.

Generic programming #

TypeScript’s generics are arguably one of the most powerful features of the language. They open a door to TypeScript’s own meta-programming language, which allows for a very flexible and dynamic generation of types. It comes really close to being its own functional programming language, as Anders Hejlsberg stated in his 2020 TSConf keynote.

Especially with the arrival of string literal types and recursive conditional types in the most recent TypeScript versions, we can craft types that do astonishing things. This little type parses Express-style route information and retrieves an object with all its parameters:

type ParseRouteParameters<T> = 
T extends `${string}/:${infer U}/${infer R}` ?
{ [P in U | keyof ParseRouteParameters<`/${R}`>]: string } :
T extends `${string}/:${infer U}` ?
{ [P in U]: string } : {}

type X = ParseRouteParameters<"/api/:what/:is/notyou/:happening">
// type X = {
// what: string,
// is: string,
// happening: string,
// }

Powerful! (Dan shows a more elaborate version of this type over at his blog, check it out).

When we define a generic type, we also define generic type parameters. That’s the stuff between the angle brackets that we sometimes causally call generics.

They can be of a certain type (or more correct: be a certain sub-type):

type Foo<T extends string> = ...

They can have default values:

type Foo<T extends string = "hello"> = ...

And when using default values, order is important. Lots of similarities to regular JavaScript functions! So since we are almost talking functions, why are we using single-letter names for generic type parameters?

Naming generic type parameters #

Most generic type parameters start with the letter T. Subsequent parameters go along the alphabet (U, V, W), or are abbreviations like K for key.

As with almost any programming concept, the idea of Generics has been around for quite some time. Some major implementations of generic types can be seen in programming languages of the Seventies, such as Ada and ML.

I don’t know if naming type parameters T has started back then, or if it was the popularity of the similar – albeit more powerful – templating concept in C++ that led us to generally calling them that way. The point is: We are doing that for a long time. We are used to it.

This can lead to highly unreadable types, however. If I look at Pick<T, U>, I can never tell if I pick keys T from object type U, or if it’s object type T, where I pick keys U.

Being a bit more elaborate helps a lot:

type Pick<Obj, Keys> = ...

Note: The actual Pick type is much better defined in TypeScript (with K extends keyof T), but you get the idea. Exclude, Extract, Record … all of them make me scratch my head.

So even though it’s common to use single letter names for our generics, I think we can do better!

A naming concept #

Types are documentation, and our type parameters can have speaking names. Just like you would do with regular functions. This is the style guide I’m using:

  1. All type parameters start with an uppercase letter. Like I would name all other types!
  2. Only use single letters if the usage is completely clear. E.g. ParseRouteParams can only have one argument, the route.
  3. Don’t abbreviate to T (that’s way too … generic! 🤨), but to something that makes it clear what we are dealing with. E.g. ParseRouteParams<R>, where R stands for Route.
  4. Rarely use single letters, stick to short words, or abbreviations. Elem for Element, Route can stand as it is.
  5. Use prefixes where I need to differentiate from built-in types. E.g. Element is taken, I can use GElement (or stick with Elem)
  6. Use prefixes to make generic names clearer URLObj is clearer than Obj, for instance.
  7. Same patterns apply to inferred types within a generic type.

Let’s look at ParseRouteParams again, and be more explicit with our names:

type ParseRouteParameters<Route> = 
Route extends `${string}/:${infer Param}/${infer Rest}` ?
{ [Entry in Param | keyof ParseRouteParameters<`/${Rest}`>]: string } :
Route extends `${string}/:${infer Param}` ?
{ [Entry in Param]: string } : {}

It becomes a lot clearer what each type is meant to be. We also see that we need to iterate over all Entries in Param, even if Param is just a set of one type.

Arguably, a lot more readable than before!

Counter arguments? Well, generic programming in TypeScript is close to functional programming. And you know that functional programming is where you name your functions f, your arguments x, and your patterns Zygohistomorphic prepromorphism. 😜

You can read a lot more on generics, how generics work in TypeScript and what they are capable of in my book TypeScript in 50 lessons.

Related Articles