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

推荐订阅源

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 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: Typing Generic forwardRefs
2021-04-13 · via oida.dev | TypeScript, Rust

If you are creating component libraries and design systems in React, you might already have fowarded Refs to the DOM elements inside your components.

This is especially useful if you wrap basic components or leafs in proxy components, but want to use the ref property just like you’re used to:

const Button = React.forwardRef((props, ref) => (
<button type="button" {...props} ref={ref}>
{props.children}
</button>
));

// Usage: You can use your proxy just like you use
// a regular button!
const reference = React.createRef();
<Button className="primary" ref={reference}>Hello</Button>

Providing types for React.forwardRef is usually pretty straightforward. The types shipped by @types/react have generic type variables that you can set upon calling React.forwardRef. In that case, explicitly annotating your types is the way to go!

type ButtonProps = JSX.IntrinsicElements["button"];

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
(props, ref) => (
<button type="button" {...props} ref={ref}>
{props.children}
</button>
)
);

// Usage
const reference = React.createRef<HTMLButtonElement>();
<Button className="primary" ref={reference}>Hello</Button>

If you want to know more about patterns on proxy components, type information on WithChildren and preset attributes, please refer to my Component Patterns guide. Also, check on useRef typings from my TypeScript + React guide for a hook-friendly alternative to React.createRef.

So far, so good. But things get a bit hairy if you have a component that accepts generic properties. Check out this component that produces a list of list items, where you can select each row with a button element:

type ClickableListProps<T> = {
items: T[];
onSelect: (item: T) => void;
};

function ClickableList<T>(props: ClickableListProps<T>) {
return (
<ul>
{props.items.map((item) => (
<li>
<button onClick={() => props.onSelect(item)}>
Choose
</button>
{item}
</li>
))}
</ul>
);
}

// Usage
const items = [1, 2, 3, 4];
<ClickableList items={items}
onSelect={(item) => {
// item is of type number
console.log(item)
} }
/>

You want the extra type-safety so you can work with a type-safe item in your onSelect callback. Say you want to create a ref to the inner ul element, how do you proceed? Let’s change the ClickableList component to an inner function component that takes a ForwardRef, and use it as an argument in the React.forwardRef function.

// The original component extended with a `ref`
function ClickableListInner<T>(
props: ClickableListProps<T>,
ref: React.ForwardedRef<HTMLUListElement>
) {
return (
<ul ref={ref}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={(el) => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}

// As an argument in `React.forwardRef`
const ClickableList = React.forwardRef(ClickableListInner)

This compiles, but has one downside: We can’t assign a generic type variable for ClickableListProps. It becomes unknown by default. Which is good compared to any, but also slightly annoying. When we use ClickableList, we know which items to pass along! We want to have them typed accordingly! So how can we achieve this? The answer is tricky… and you have a couple of options.

Option 1: Type assertion #

One option would be to do a type assertion that restores the original function signature.

const ClickableList = React.forwardRef(ClickableListInner) as <T>(
props: ClickableListProps<T> &
{ ref?: React.ForwardedRef<HTMLUListElement> }
) => ReturnType<typeof ClickableListInner>;

Type assertions are a little bit frowned upon as they look similar like type casts in other programming languages. They are a little bit different, and Dan masterfully explains why. Type assertions have their place in TypeScript. Usually, my approach is to let TypeScript figure out everything from my JavaScript code that it can figure out on its own. Where it doesn’t, I use type annotations to help a little bit. And where I know definitely more than TypeScript, I do a type assertion.

This is one of these cases, here I know that my original component accepts generic props!

Option 2: Create a custom ref / The Wrapper Component #

While ref is a reserved word for React components, you can use your own, custom props to mimic a similar behavior. This works just as well.

type ClickableListProps<T> = {
items: T[];
onSelect: (item: T) => void;
mRef?: React.Ref<HTMLUListElement> | null;
};

export function ClickableList<T>(
props: ClickableListProps<T>
) {
return (
<ul ref={props.mRef}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={(el) => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}

You introduce a new API, though. For the record, there is also the possibility of using a wrapper component, that allows you to use forwardRefs inside in an inner component and expose a custom ref property to the outside. This circulates around the web, I just see no significant benefit compared to the previous solution – enlighten me if you know one!.

function ClickableListInner<T>(
props: ClickableListProps<T>,
ref: React.ForwardedRef<HTMLUListElement>
) {
return (
<ul ref={ref}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={(el) => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}

const ClickableListWithRef = forwardRef(ClickableListInner);

type ClickableListWithRefProps<T> = ClickableListProps<T> & {
mRef?: React.Ref<HTMLUListElement>;
};

export function ClickableList<T>({
mRef,
...props
}: ClickableListWithRefProps<T>) {
return <ClickableListWithRef ref={mRef} {...props} />;
}

Both are valid solutions if the only thing you want to achieve is passing that ref. If you want to have a consistent API, you might look for something else.

Option 3: Augment forwardRef #

This is actually my most favourite solution.

TypeScript has a feature called higher-order function type inference, that allows propagating free type parameters on to the outer function.

This sounds a lot like what we want to have with forwardRef to begin with, but for some reason it doesn’t work with our current typings. The reason is that higher-order function type inference only works on plain function types. the function declarations inside forwardRef also add properties for defaultProps, etc. Relics from the class component days. Things you might not want to use anyway.

So without the additional properties, it should be possible to use higher-order function type inference!

And hey! We are using TypeScript, we have the possibility to redeclare and redefine global module, namespace and interface declarations on our own. Declaration merging is a powerful tool, and we’re going to make use of it.

// Redecalare forwardRef
declare module "react" {
function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactNode | null
): (props: P & React.RefAttributes<T>) => React.ReactNode | null;
}

// Just write your components like you're used to!

type ClickableListProps<T> = {
items: T[];
onSelect: (item: T) => void;
};
function ClickableListInner<T>(
props: ClickableListProps<T>,
ref: React.ForwardedRef<HTMLUListElement>
) {
return (
<ul ref={ref}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={(el) => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}

export const ClickableList = React.forwardRef(ClickableListInner);

The nice thing about this solution is that you write regular JavaScript again, and work exclusively on a type level. Also, redeclarations are module-scoped. No interference with any forwardRef calls from other modules!

Credits #

This article comes from a discussion with Tom Heller as we had a case like this in our component library. While we came up with option 1, the assertion on our own, we did some digging to see if there are more options. This StackOverflow discussion – especially the feedback from User ford04 brought up new perspectives. Big shout-out to them!

I also put up a Codesandbox where you can try out all the solutions on your own.

Related Articles