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

推荐订阅源

人人都是产品经理
人人都是产品经理
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: 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: 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 + React: Children types are broken
2021-09-15 · via oida.dev | TypeScript, Rust

Update April 2022: With the update to React 18, a lot of those problems have been fixed. See this pull request for more details

I currently work with a couple of newcomers to React and teach them both TypeScript and React to create apps. It’s fun, and for me who’s been using that for a while now, it’s a great way of seeing this piece of tech through fresh eyes.

It’s also great to see that some of them use React in a way you’d never envisioned it. What’s not so great is if you encounter situations where React throws an error (and possibly crashes your app), where TypeScript doesn’t even flinch. One of these situations happened recently, and I fear there won’t be an easy fix to it.

The Problem #

Consider the following component. It’s a card, it takes a title and renders arbitrary children. I use my own WithChildren helper type (see React patterns), but the same is true if you use FC from the provisioned @types/react package.

type WithChildren<T = {}> = T & { children?: React.ReactNode };

type CardProps = WithChildren<{
title: string;
}>;

function Card(props: CardProps) {
return (
<div className="card">
<h2>{props.title}</h2>
{props.children}
</div>
);
};

So far, so good. Now let’s use this component with some React nodes:

export default function App() {
return (
<div className="App">
<Card title="Yo!">
<p>Whats up</p>
</Card>
</div>
);
}

Compiles. Renders! Great. Now let’s use it with an arbitrary, random object:

export default function App() {
const randomObject = {};
return (
<div className="App">
<Card title="Yo!">{randomObject}</Card>
</div>
);
}

This compiles as well, TypeScript doesn’t throw an error at all. But this is what you get from your browser:

Error

Objects are not valid as a React child (found: object with keys {}).
If you meant to render a collection of children, use an array instead.

Oh no! TypeScript’s worldview is different from what we actually get from the library. This is bad. This is really bad. That’s situations TypeScript should check. So what’s happening?

The culprit #

There’s one line in the React types from Definitely Typed that disables type checking for children almost entirely. It’s currently on line 236, and looks like that:

interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

With the definition of ReactFragment to allow {}, we basically allow passing any object whatsoever (anything but null or undefined, but just look at the next line!). Since TypeScript is structurally typed, you can pass in everything that is a subtype of the empty object. Which in JavaScript, is everything!

The problem is: This is not a new change, it has been around for almost forever. It was introduced in March 2015, and nobody knows why. We also don’t know if the semantics back then would’ve been different.

Many folks pointed this out (see here, here, here, and here), and some folks tried to fix it.

But since it’s been around for 6+ years, this little change breaks a ton of packages directly connect to the React types. This is a huge change that is really tough to handle! So honestly, I’m not sure if we reasonably can update this line. Even worse: All those packages have the wrong tests and types. I don’t know what to think of that.

What can we do about it #

But we can always define our children types on our own. If you use WithChildren, it becomes even easier. Let’s create our own ReactNode:


import type { ReactChild, ReactPortal, ReactNodeArray } from "react";

type ReactNode =
| ReactChild
| ReactNodeArray
| ReadonlyArray<ReactNode>
| ReactPortal
| boolean
| null
| undefined;

type WithChildren<T = {}> = T & { children?: ReactNode };

type CardProps = WithChildren<{
title: string;
}>;

With that, we get the errors we want:


export default function App() {
const randomObject = {};
return (
<div className="App">
<Card title="Yo!">{randomObject}</Card>{/* 💥 BOOM! */}
</div>
);
}

And TypeScript is in tune with the real world again.

This is especially useful if you provide a couple of components to others! The moment e.g. some back-end data changes from being a simple string to a complex object, you spot all the problems in your codebase at once, and not through crashes in your application at runtime.

Caveats #

This works great if you are in your own codebase. The moment you need to combine your safe components with other components that e.g. use React.ReactNode or FC<T>, you might run into errors again, because the types won’t match. I haven’t encountered this but never say never.

Bottom line #

I keep asking myself if this little issue is really a problem as I myself have worked fine for years without knowing that ReactNode can basically be everything in TypeScript. Newcomers might be a bit more worried about their software not behaving as the types suggest. How can we fix that? I’m open for ideas.

Also hat tip to Dan for being the best post-release tech editor you can wish for 😉

Related Articles