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

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

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 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 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: Improving Object.keys
2020-06-17 · via oida.dev | TypeScript, Rust

Note: Be very careful with this technique. Better checkout my new approach.

TypeScript’s predefined types in lib.d.ts are usually very well-typed and give tons of information on how to use built-in functionality as well as providing you with extra-type safety. Until they don’t. Consider the following example with an object type Person:

type Person = {
name: string, age: number, id: number,
}
declare const me: Person;

Object.keys(me).forEach(key => {
// 💥 the next line throws red squigglies at us
console.log(me[key])
})

We have an object of type Person, with Object.keys we want to get all keys as strings, then use this to access each property in a map or forEach loop to do something about it in strict mode, we get red squigglies thrown at us. This is the error message:

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Person’. No index signature with a parameter of type ‘string’ was found on type ‘Person’

So what’s happening? The type declaration for Object.keys is as follows:

interface ObjectConstructor {
//...
keys(o: object): string[]
keys(o: {}): string[]
}

Both overloads take any object as input and return a string array as output. This is correct and expected behavior. It’s just very generalized for something where we already know more, and where TypeScript should know more.

string is a super-set of the actual keys we can access from Person. The concrete subset would be name | age | id. This is also the set of values TypeScript allows us to index from Person. For every other string, TypeScript says that it could be, but the indexed value could be any-thing. And in strict mode, any is not allowed unless explicitly stated.

Important: There is most likely a reason for this. Either more concrete types cause problems somewhere in well-established libraries. Or the behavior is too complex to be summed up in a type. Or, there simply were more important things. This doesn’t mean that better typings won’t come at some point.

But still, what can we do?

Option 1. Type-casting #

The worst solution would be to turn off noImplicitAny. This is an open door for bugs and wrong types. The most obvious solution would be type-casting. We could either cast the object to any to allow for … everything to happen.

Object.keys(me).forEach((key) => {
console.log((me as any)[key])
})

Not cool. Or we can cast the key argument to be of keyof Person to ensure TypeScript understands what we’re aiming for.

Object.keys(me).forEach((key) => {
console.log(me[key as keyof Person])
})

Better. Still not cool. This is something TypeScript should do on its own! So if TypeScript doesn’t know yet, we can start teaching TypeScript how to do it.

Option 2. Extending Object Constructor #

Thanks to the declaration merging feature of interfaces, we can extend the ObjectConstructor interface with our own type definitions. We can do this directly where we need it or create our own ambient declaration file.

We open the interface, and write another overload for keys. This time we want to be very concrete about the object’s value we get in and decide based on its shape what to return.

This is the behavior:

  1. If we pass a number, we get an empty array.
  2. If we pass a string or an array, we get a string array in return. This string array contains string representations of the number indices to index either the array or the string’s position. Meaning that the string array has the same length as its input.
  3. For any real object, we return its keys.

We construct a helper type for this. This one is a conditional type, describing the behavior above.

type ObjectKeys<T> = 
T extends object ? (keyof T)[] :
T extends number ? [] :
T extends Array<any> | string ? string[] :
never;

In my conditional types, I usually end on never. This gives me the first signal that I either forget something in my declaration or did something entirely wrong in my code. In any case, it’s a good pointer to see that something’s smelly.

Now, we open the ObjectConstructor interface and add another overload for keys. We define a generic type variable, the return value is based on the conditional type ObjectKeys.

interface ObjectConstructor {
keys<T>(o: T): ObjectKeys<T>
}

Again, since this is an interface, we can monkey-patch our definitions right where we need them. The moment we pass a concrete object to Object.keys, we bind the generic type variable T to this object. Meaning that our conditional can give exact information about the return value. And since our definition is the most specific of all three keys declarations, TypeScript defaults to using this.

Our little example doesn’t throw squigglies at us anymore.

Object.keys(me).forEach((key) => {
// typeof key = 'id' | 'name' | 'age'
console.log(me[key])
})

The type of key is now 'id' | 'name' | 'age', just as we want it to be. Also, for all other cases, we get proper return values.

Note: The behavior of passing an array or a string doesn’t significantly change. But this is a good indicator that there might be something wrong with your code. Same with the empty array. Still, we retain the behavior of built-in functionality.

Extending existing interfaces is a great way to opt-in to typings where for some reason we don’t get the information we need.

Hat tip to Mirjam who worked with me on that solution 👏

Further reading #

Dan Vanderkam pointed me to Anders’ issue on why Object.keys does not return keyof T. Read this GitHub issue comment for more details. The TLDR: While keyof T is valid in the type-level world, in run-time objects can have a lot more keys. Lenz also has a great example for that.

The question is what you expect from your type’s contract and how you work with Object.keys in general. So be sure to handle this patch with care!

Dan also pointed me to an article of his where he detailed his strategies of iterating over objects. Be sure to check it out!

Related Articles