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

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

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 + 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 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
TypeScript: Array.includes on narrow types
2021-07-06 · via oida.dev | TypeScript, Rust

The Array.prototype.includes function allows searching for a value within an array. If this value is present, the function returns true! How handy! Of course, TypeScript has proper typings for this JavaScript functionality.

However, in certain cases, the typings can bite a little. The reason? It’s complicated! Let’s find out why.

Take this little snippet for example. We create an array called actions, which contains a set of actions in string format which we want to execute. The resulting type of this actions array is string[].

The execute function takes any string as an argument. We check if this is a valid action, and if so, do something!

// actions: string[]
const actions = ["CREATE", "READ", "UPDATE", "DELETE"];

function execute(action: string) {
if(actions.includes(action)) { // 👍
// do something with action
}
}

It gets a little trickier if we want to narrow down the string[] to something more concrete, a subset of all possible strings. By adding const-context via as const, we can narrow down actions to be of type readonly ["CREATE", "READ", "UPDATE", "DELETE"].

This is handy if we want to do exhaustiveness checking to make sure we have cases for all available actions. However, actions.includes does not agree with us:

// Adding const context
// actions: readonly ["CREATE", "READ", "UPDATE", "DELETE"]
const actions = ["CREATE", "READ", "UPDATE", "DELETE"] as const;

function execute(action: string) {
if(actions.includes(action)) { // 💥 ERROR
// no can do
}
}

The error reads: Argument of type ‘string’ is not assignable to parameter of type ‘“CREATE” | “READ” | “UPDATE” | “DELETE”’. – Error 2345

So why is that? Let’s look at the typings of Array<T> and ReadonlyArray<T> (we work with the latter one due to const-context).

interface Array<T> {
/**
* Determines whether an array includes a certain element,
* returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which
* to begin searching for searchElement.
*/

includes(searchElement: T, fromIndex?: number): boolean;
}

interface ReadonlyArray<T> {
/**
* Determines whether an array includes a certain element,
* returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which
* to begin searching for searchElement.
*/

includes(searchElement: T, fromIndex?: number): boolean;
}

The element we want to search for (searchElement) needs to be of the same type as the array itself! So if we have Array<string> (or string[] or ReadonlyArray<string>), we can only search for strings. In our case, this would mean that action needs to be of type "CREATE" | "READ" | "UPDATE" | "DELETE".

Suddenly, our program doesn’t make a lot of sense anymore. Why do we search for something if the type already tells us that it just can be one of four strings? If we change the type for action to "CREATE" | "READ" | "UPDATE" | "DELETE", actions.includes becomes obsolete. If we don’t change it, TypeScript throws an error at us, and rightfully so!

One of the problems is that TypeScript lacks the possibility to check for contra-variant types with e.g. upper-bound generics. We can tell if a type should be a subset of type T with constructs like extends, we can’t check if a type is a superset of T. At least not yet!

So what can we do?

Option 1: Re-declare ReadonlyArray #

One of the options that come into mind is changing how includes in ReadonlyArray should behave. Thanks to declaration merging, we can add our own definitions for ReadonlyArray that is a bit looser in the arguments, and more specific in the result. Like this:

interface ReadonlyArray<T> {
includes(searchElement: any, fromIndex?: number): searchElement is T;
}

This allows for a broader set of searchElements to be passed (literally any!), and if the condition is true, we tell TypeScript through a type predicate that searchElement is T (the subset we are looking for).

Turns out, this works pretty well!

const actions = ["CREATE", "READ", "UPDATE", "DELETE"] as const;

function execute(action: string) {
if(actions.includes(action)) {
// action: "CREATE" | "READ" | "UPDATE" | "DELETE"
}
}

Hold your horses! First of all, there’s a problem (otherwise the TypeScript team would’ve changed that already). The solution works but takes the assumption of what’s correct and what needs to be checked. If you change action to number, TypeScript would usually throw an error that you can’t search for that kind of type. actions only consists of strings, so why even look at number. This is an error you want to catch!.

// type number has no relation to actions at all
function execute(action: number) {
if(actions.includes(action)) {
// do something
}
}

With our change to ReadonlyArray, we lose this check as searchElement is any. While the functionality of action.includes still works as intended, we might not see the right problem once we change function signatures along the way.

Also, and more importantly, we change behavior of built-in types. This might change your type-checks somewhere else, and might cause problems in the long run! If you do a “type patch” like this, be sure to do this module scoped, and not globally.

There is another way.

Option 2: A helper with type assertions #

As originally stated, one of the problems is that TypeScript lacks the possibility to check if a value belongs to a superset of a generic parameter. With a helper function, we can turn this relationship around!

function includes<T extends U, U>(coll: ReadonlyArray<T>, el: U): el is T {
return coll.includes(el as T);
}

This includes function takes the ReadonlyArray<T> as an argument, and searches for an element that is of type U. We check through our generic bounds that T extends U, which means that U is a superset of T (or T is a subset of U). If the method returns true, we can say for sure that el is of the narrower type U.

The only thing that we need to make the implementation work is to do a little type assertion the moment we pass el to Array.prototype.includes. The original problem is still there! The type assertion el as T is ok though as we check possible problems already in the function signature.

This means that the moment we change e.g. action to number, we get the right booms throughout our code.

function execute(action: number) {
if(includes(actions, action)) { // 💥
// Do Something
}
}

Since I haven’t got shiki-twoslash running yet (sorry, Orta), you can’t see where TypeScript throws the error. But I invite you to check it for yourself. The interesting thing is since we swapped the relationship and check if the actions array is a subset of action, TypeScript tells us we need to change the actions array.

Argument of type ‘readonly [“CREATE”, “READ”, “UPDATE”, “DELETE”]’ is not assignable to parameter of type ‘readonly number[]’. – Error 2345

But hey, I think that’s ok for the correct functionality we get! So let’s get ready to do some exhaustiveness checking:


function assertNever(input: never) {
throw new Error("This is never supposed to happen!")
}

function execute(action: string) {
if(includes(actions, action)) {
// action: "CREATE" | "READ" | "UPDATE" | "DELETE"
switch(action) {
case "CREATE":
// do something
break;
case "READ":
// do something
break;
case "UPDATE":
// do something
break;
case "DELETE":
// do something
break;
default:
assertNever(action)
}
}
}

Great!

On a side note, the same solutions also work if you run into similar troubles with Array.prototype.indexOf!

Bottom line #

TypeScript aims to get all standard JavaScript functionality correct and right, but sometimes you have to make trade-offs. This case brings calls for trade-offs: Do you allow for an argument list that’s looser than you would expect, or do you throw errors for types where you already should know more?

Type assertions, declaration merging, and other tools help us to get around that in situations where the type system can’t help us. Not until it becomes better than before, by allowing us to move even further in the type space!

And, as always, here’s a playground for you to fiddle around! Here’s also a a great issue to read up on that.

Related Articles