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

推荐订阅源

美团技术团队
T
The Exploit Database - CXSecurity.com
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
T
Tailwind CSS Blog
V
V2EX
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
PCI Perspectives
PCI Perspectives
腾讯CDC
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Commits to openclaw:main
Recent Commits to openclaw:main
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
N
News and Events Feed by Topic
博客园 - 三生石上(FineUI控件)
Help Net Security
Help Net Security
雷峰网
雷峰网
有赞技术团队
有赞技术团队
Last Week in AI
Last Week in AI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
量子位
GbyAI
GbyAI
O
OpenAI News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AI
AI
S
Security Affairs
F
Fortinet All Blogs
L
LINUX DO - 最新话题
博客园 - 【当耐特】
Webroot Blog
Webroot Blog
Schneier on Security
Schneier on Security
W
WeLiveSecurity
Security Latest
Security Latest
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tenable Blog
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
Simon Willison's Weblog
Simon Willison's Weblog
Cyberwarzone
Cyberwarzone
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
CERT Recently Published Vulnerability Notes
Engineering at Meta
Engineering at Meta
P
Palo Alto Networks Blog
博客园 - 叶小钗
T
Threatpost
H
Heimdal Security Blog
Microsoft Security Blog
Microsoft Security 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: 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 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: 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: Validate mapped types and const context
2019-08-26 · via oida.dev | TypeScript, Rust

Mapped types are great, as they allow for the flexibility in object structures JavaScript is known for. But they have some crucial implications on the type system. Take this example:

type Messages = 
'CHANNEL_OPEN' | 'CHANNEL_CLOSE' | 'CHANNEL_FAIL' |
'MESSAGE_CHANNEL_OPEN' | 'MESSAGE_CHANNEL_CLOSE' |
'MESSAGE_CHANNEL_FAIL'

type ChannelDefinition = {
[key: string]: {
open: Messages,
close: Messages,
fail: Messages
}
}

This is from a generic messaging library, that takes a “channel definition” where multiple channel tokens can be defined. The keys from this channel definition object are what the user wants it to be. So this is a valid channel definition:

const impl: ChannelDefinition = {
test: {
open: 'CHANNEL_OPEN',
close: 'CHANNEL_CLOSE',
fail: 'CHANNEL_FAIL'
},
message: {
open: 'MESSAGE_CHANNEL_OPEN',
close: 'MESSAGE_CHANNEL_CLOSE',
fail: 'MESSAGE_CHANNEL_FAIL'
}
}

We have a problem when we want to access the keys we defined so flexibly. Let’s say we have a function that opens a channel. We pass the whole channel definition object, as well as the channel we want to open.

declare function openChannel(
def: ChannelDefinition,
channel: keyof ChannelDefinition
)

So what are the keys of ChannelDefinition? Well, it’s every key: [key: string]. So the moment we assign a specific type, TypeScript treats impl as this specific type, ignoring the actual implementation. The contract is fulfilled. Moving on. This allows for wrong keys to be passed:

// Passes, even though "massages" is no part of impl
openChannel(impl, 'massages')

So we are more interested in the actualy implementation, not the type we assing to our constant. This means we have to get rid of the ChannelDefinition type and make sure we care about the actual type of the object.

First, the openChannel function should take any object that is a subtype of ChannelDefinition, but work with the concrete subtype:

- declare function openChannel(
- def: ChannelDefinition,
- channel: keyof ChannelDefinition
- )
+ declare function openChannel<T extends ChannelDefinition>(
+ def: T,
+ channel: keyof T
+ )

TypeScript now works on two levels:

  1. Checking if T actually extends ChannelDefinition. If so, we work with type T
  2. All our function parameters are typed with the generic T. This also means we get the real keys of T through keyof T.

To benefit from that, we have to get rid of the type definition for impl. The explicit type definition overrides all actual types. From the moment we explicitly specify the type, TypeScript treats it as ChannelDefinition, not the actual underlying subtype. We also have to set const context, so we can convert all strings to their unit type (and thus be compliant with Messages):

- const impl: ChannelDefinition = { ... };
+ const impl: { ... } as const;

Without const context, the inferred type of implis:

/// typeof impl 
{
test: {
open: string;
close: string;
fail: string;
};
message: {
open: string;
close: string;
fail: string;
};
}

With const context, the actual type of impl is now:

/// typeof impl 
{
test: {
readonly open: "CHANNEL_OPEN";
readonly close: "CHANNEL_CLOSE";
readonly fail: "CHANNEL_FAIL";
};
message: {
readonly open: "MESSAGE_CHANNEL_OPEN";
readonly close: "MESSAGE_CHANNEL_CLOSE";
readonly fail: "MESSAGE_CHANNEL_FAIL";
};
}

const context allows us to satisfy the contract made by ChannelDefinition. Now, openChannel correctly errors:

openChannel(impl, 'messages') // ✅ satisfies contract
openChannel(impl, 'massages') // 💥 bombs

You might be in a space where you need to work with the concrete type, that satisfies the ChannelDefinition contract, outside of a function. For that, we can mimic the same behaviour using the Validate<T, U> helper type:

type Validate<T, U> = T extends U ? T : never; 

Use this as follows:

const correctImpl = {
test: {
open: 'CHANNEL_OPEN', close: 'CHANNEL_CLOSE', fail: 'CHANNEL_FAIL'
}
} as const;

const wrongImpl = {
test: {
open: 'OPEN_CHANNEL', close: 'CHANNEL_CLOSE', fail: 'CHANNEL_FAIL'
}
} as const;

// ✅ returns typeof correctImpl
type ValidatedCorrect
= Validate<typeof correctImpl, ChannelDefinition>;

// 💥 returns never
type ValidatedWrong
= Validate<typeof wrongImpl, ChannelDefinition>;

As always, there’s a pen for you to fiddle around.

Related Articles