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

推荐订阅源

K
Kaspersky official blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
Intezer
Scott Helme
Scott Helme
A
About on SuperTechFans
博客园 - 司徒正美
Hacker News: Ask HN
Hacker News: Ask HN
The GitHub Blog
The GitHub Blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
S
Security Affairs
宝玉的分享
宝玉的分享

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 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: Prefer type aliases over interfaces
2020-11-20 · via oida.dev | TypeScript, Rust

This is the second article in a series of articles where I want to highlight ways on how to keep your TypeScript code neat and tidy. By nature, this series is heavily opinionated and is to be taken with grains of salt (that’s plural).

There are two different ways in TypeScript to declare object types: Interfaces and type aliases. Both approaches to defining object types have been subject to lots of blog articles over the years. And all of them became outdated as time progressed. Right now, there is little difference between type aliases and interfaces. And everything that was different has been gradually aligned.

Syntactically, their difference is nuanced:

type PersonAsType = {
name: string;
age: number;
address: string[];
greet(): string;
};

interface PersonAsInterface {
name: string;
age: number;
address: string[];
greet(): string;
}

It’s an equal sign. This nuance can have some effect on the time of type evaluation – immediate for the type alias, lazy for interfaces – but that’s it. You can use interfaces and type aliases for the same things, in the same scenarios:

  • In an implements declaration for classes
  • As a type annotation for object literals
  • For recursive type structures

You name it! There is however one important difference that can have side effects you usually don’t want to deal with:

Declaration merging #

Interfaces allow for declaration merging, type aliases don’t. Declaration merging allows for adding properties to an interface even after it has been declared.

interface Person {
name: string;
}

interface Person {
age: number;
}

// Person is now { name: string; age: number; }

TypeScript itself uses this technique a lot in lib.d.ts files, making it possible to just add deltas of new JavaScript APIs based on ECMAScript versions. This is a great feature if you want to extend e.g. Window, but it can fire back in other scenarios. Take this as an example:

// Some data we collect in a web form
interface FormData {
name: string;
age: number;
address: string[];
}

// A function that sends this data to a back-end
function send(data: FormData) {
console.log(data.entries()) // this compiles!! 😱
// but crashes horrendously in runtime 😕
}

Oh, bother, where does the entries() method come from? It’s a DOM API! FormData is one of the interfaces provided by browser APIs, and there are a lot of them. They are globally available, and nothing keeps you from extending those interfaces. And you get no notification if you do.

We can of course argue about proper naming, but the problem persists for all interfaces that you make available globally, maybe from some dependency where you don’t even know they add an interface like that to the global space.

Changing this interface to a type alias immediately makes you aware of this problem:

type FormData = {
// ^ 💥 Duplicate identifier 'FormData'.(2300)
name: string;
age: number;
address: string[];
}

It also prevents your types from being extended unknowingly.

Index access types #

Declaration merging is also the reason why interfaces won’t work as a subset of index access types. Below is an example that sends data to a server. You can pass in any object and a set of HTTP headers that require all keys to be of string and all values to be of string.

declare function 
send(data: any, headers: Record<string, string>): void;

Record<string, string> is the same as { [key: string]: string }, which shows the flexible index access better.

Let’s do two type definitions for required HTTP headers. Once as object type:

type HTTPHeaders = {
Accept: string,
Cookie: string
}

And another one as an interface:

interface HTTPHeaderInterface {
Accept: string,
Cookie: string,
}

If you call send with an object that has been annotated as HTTPHeaders, everything is wonderful:

const hdrs: HTTPHeaders = {
Accept: "text/html",
Cookie: ""
};

send({}, hdrs) // 👍

But the moment you change hdrs to HTTPHeadersInterface, things go boom:

const hdrs: HTTPHeaderInterface = {
Accept: "text/html",
Cookie: ""
};

send({}, hdrs)
// ^ 💥 Index signature is missing in type 'HTTPHeaderInterface'

TypeScript will complain that the index signature is missing. Only if the type is final, like with HTTPHeaders, TypeScript can correctly check if all properties and values are assignable to the Record<string, string> type we declared in send. Since interfaces are up for declaration merging, and therefore not all properties are known, TypeScript can’t tell if the index signature is compatible with Record<string, string>.

That’s why I suggest to prefer type aliases over interfaces. Of course, if you are providing a library that has interfaces that should be extendable by others, type aliases won’t get you far. But other than that, type aliases are clear, simple, and tidy.

Related Articles