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

推荐订阅源

K
Kaspersky official blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
Intezer
Scott Helme
Scott Helme
A
About on SuperTechFans
博客园 - 司徒正美
Hacker News: Ask HN
Hacker News: Ask HN
The GitHub Blog
The GitHub Blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
S
Security Affairs
宝玉的分享
宝玉的分享

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: 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: Component patterns
2020-07-28 · via oida.dev | TypeScript, Rust

This list is a collection of component patterns for React when working with TypeScript. See them as an extension to the TypeScript + React Guide that deals with overall concepts and types. This list has been heavily inspired by chantastic’s original React patterns list.

Contrary to chantastic’s guide I use mainly modern-day React, so function components and – if necessary – hooks. I also focus exclusively on types.

Last updated: July 30, 2020

Have fun!

Table of Contents #

  • Basic function components
  • Props
  • Default Props
  • Children
  • WithChildren Helper type
  • Spread attributes
  • Preset attributes
  • Styled components
  • Required properties
  • Controlled input

Basic function components #

When using function components without any props you don’t have the need to use extra types. Everything can be inferred. In old-style functions (which I prefer), as well as in arrow functions.

function Title() {
return <h1>Welcome to this application</h1>;
}

Props #

When using props we name props usually according to the component we’re writing, with a Props-suffix. No need to use FC component wrappers or anything similar.

type GreetingProps = {
name: string;
};

function Greeting(props: GreetingProps) {
return <p>Hi {props.name} 👋</p>
}

Destructuring makes it even more readable

function Greeting({ name }: GreetingProps) {
return <p>Hi {name} 👋</p>;
}

Default props #

Instead of setting default props, like in class-based React, it’s easier to set default values to props. We mark props with a default value optional (see the question-mark operator). The default value makes sure that name is never undefined.

type LoginMsgProps = {
name?: string;
};

function LoginMsg({ name = "Guest" }: LoginMsgProps) {
return <p>Logged in as {name}</p>;
}

Children #

Instead of using FC or FunctionComponent helpers we prefer to set children explicitly, so it follows the same pattern as other components. We set children to type React.ReactNode as it accepts most (JSX elements, strings, etc.)

type CardProps = {
title: string;
children: React.ReactNode;
};

export function Card({ title, children }: CardProps) {
return (
<section className="cards">
<h2>{title}</h2>
{children}
</section>
);
}

When we set children explicitly, we can also make sure that we never pass any children.

// This throws errors when we pass children
type SaveButtonProps = {
//... whatever
children: never
}

See my arguments why I don’t use FC in this editoral.

WithChildren helper type #

A custom helper type helps us to set children easier.

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

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

This is very similar to FC, but with the default generic parameter to {}, it can be much more flexible:

// works as well
type CardProps = { title: string } & WithChildren;

If you are using Preact, you can use h.JSX.Element or VNode as a type instead of React.ReactNode.

Spread attributes to HTML elements #

Spreading attributes to HTML elements is a nice feature where you can make sure that you are able to set all the HTML properties that an element has without knowing upfront which you want to set. You pass them along. Here’s a button wrapping component where we spread attributes. To get the right attributes, we access a button’s props through JSX.IntrinsicElements. This includes children, we spread them along.

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

function Button({ ...allProps }: ButtonProps) {
return <button {...allProps} />;
}

Preset attributes #

Let’s say we want to preset type to button as the default behavior submit tries to send a form, and we just want to have things clickable. We can get type safety by omitting type from the set of button props.

type ButtonProps =
Omit<JSX.IntrinsicElements["button"], "type">;

function Button({ ...allProps }: ButtonProps) {
return <button type="button" {...allProps} />;
}

// 💥 This breaks, as we omitted type
const z = <Button type="button">Hi</Button>;

Styled components #

Not to be confused with the styled-components CSS-in-JS library. We want to set CSS classes based on a prop we define. E.g. a new type property that allows being set to either primary or secondary.

We omit the original type and className and intersect with our own types:

type StyledButton = Omit<
JSX.IntrinsicElements["button"],
"type" | "className"
> & {
type: "primary" | "secondary";
};

function StyledButton({ type, ...allProps }: StyledButton) {
return <Button className={`btn-${type}`} />;
}

Required properties #

We dropped some props from the type definition and preset them to sensible defaults. Now we want to make sure our users don’t forget to set some props. Like the alt attribute of an image or the src attribute.

For that, we create a MakeRequired helper type that removes the optional flag.

type MakeRequired<T, K extends keyof T> = Omit<T, K> &
Required<{ [P in K]: T[P] }>;

And build our props with that:

type ImgProps 
= MakeRequired<
JSX.IntrinsicElements["img"],
"alt" | "src"
>;

export function Img({ alt, ...allProps }: ImgProps) {
return <img alt={alt} {...allProps} />;
}

const zz = <Img alt="..." src="..." />;

Controlled Input #

When you use regular input elements in React and want to pre-fill them with values, you can’t change them anymore afterward. This is because the value property is now controlled by React. We have to put value in our state and control it. Usually, it’s enough to just intersect the original input element’s props with our own type. It’s optional as we want to set it to a default empty string in the component later on.

type ControlledProps = 
JSX.IntrinsicElements["input"] & {
value?: string;
};

Alternatively, we can drop the old property and rewrite it:

type ControlledProps =
Omit<JSX.IntrinsicElements["input"], "value"> & {
value?: string;
};

And use useState with default values to make it work. We also forward the onChange handler we pass from the original input props.

function Controlled({
value = "", onChange, ...allProps
}: ControlledProps) {
const [val, setVal] = useState(value);
return (
<input
value={val}
{...allProps}
onChange={e => {
setVal(() => e.target?.value);
onChange && onChange(e);
}}
/>
);
}

to be extended

Play around #

Instead of the usual TypeScript playground, I created a Codesandbox you can use to play around. Have fun!

Related Articles