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

推荐订阅源

Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
SecWiki News
SecWiki News
N
News | PayPal Newsroom
T
Tor Project blog
W
WeLiveSecurity
A
Arctic Wolf
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
月光博客
月光博客
AWS News Blog
AWS News Blog
D
Docker
C
CERT Recently Published Vulnerability Notes
MyScale Blog
MyScale Blog
Google Online Security Blog
Google Online Security Blog
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
I
InfoQ
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
D
DataBreaches.Net
S
Security Affairs
WordPress大学
WordPress大学
T
Threatpost
Microsoft Security Blog
Microsoft Security Blog
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
B
Blog RSS Feed
Project Zero
Project Zero
P
Proofpoint News Feed

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