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

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Define function overload types with TypeScript
2021-01-12 · via Kent C. Dodds Blog

Allow me to quickly answer to the "normal" use case of "How to define function overload types with TypeScript" with an example:

I want a function that accepts a callback or returns a promise if none is provided:

const logResult = (result) => console.log(`result: ${result}`)
asyncAdd(1, 2).then(logResult) // logs "result: 3"
asyncAdd(3, 6, logResult) // logs "result: 9"

Here's how you'd implement this API using regular JavaScript:

function asyncAdd(a, b, cb) {
	const result = a + b
	if (cb) return cb(result)
	else return Promise.resolve(result)
}

With this implementation, what we want is to have TypeScript catch this bad usage:

// @ts-expect-error because when the cb is provided, void is returned so you can't use ".then"!
asyncAdd(1, 2, logResult).then(logResult) // this would throw an error when trying to use ".then" (except we're using TypeScript so it won't even compile 😉)

So, here's how you'd type this kind of overloading:

type asyncAddCb = (result: number) => void
// define all valid function signatures
function asyncAdd(a: number, b: number): Promise<number>
function asyncAdd(a: number, b: number, cb: asyncAddCb): void

// define the actual implementation
// notice cb is optional
// also notice that the return type is inferred, but it could be specified as `void | Promise<number>`
function asyncAdd(a: number, b: number, cb?: asyncAddCb) {
	const result = a + b
	if (cb) return cb(result)
	else return Promise.resolve(result)
}

And then you're off to the races!

Dig deeper

The real inspiration for this blog post is a bit more complicated though and requires some background information:

I have a package called babel-plugin-codegen that allows you to generate code at compile time. For example, assume you have a file with the following code:

// @codegen
const fs = require('fs')
const fruits = fs.readFileSync('./fruit.txt', 'utf8').toString().split('\n')
module.exports = fruits
	.map((fruit) => `export const ${fruit} = '${fruit}';`)
	.join('')

Assuming fruit.txt contains a list of fruits, this is what that'll compile to:

export const apple = 'apple'
export const orange = 'orange'
export const pear = 'pear'

So, you generate a string of code, and codegen turns that to actual code that's fed into your output. This unlocks a lot of really cool things.

But the specifics of this babel plugin doesn't matter. What does matter is that you can also use this with babel-plugin-macros which is basically importable babel transforms. So instead of configuring babel-plugin-codegen, you can just configure babel-plugin-macros and then install codegen.macro and you can import and use it like so:

import codegen from 'codegen.macro'

// using as a tagged template literal:
codegen`
  module.exports = "const tag = 'this is an example'"
`

// using as a function
codegen(`
  module.exports = "const fn = 'this is another example'"
`)

// codegen-ing an external module (and pass an argument):
const jpgs = codegen.require('./get-files-list', '**/*.jpg')

const ui = <Codegen>{`module.exports = require('./some-jsx-code')`}</Codegen>

Then that could compile to something like this:

// using as a tagged template literal:
const tag = 'this is an example'

// using as a function
const fn = 'this is another example'

// codegen-ing an external module (and pass an argument):
const jpgs = ['kody.jpg', 'olivia.jpg', 'marty.jpg']

const ui = <div>This is some example JSX code</div>

Anyway, codegen is pretty sweet. But you'll notice there's some hard-core overloading going here, so I thought I'd share how I typed this function overloading with TypeScript.

Function Overloading with TypeScript

Something really important to keep in mind is that the actual codegen function implementation is actually a babel macro, so it looks nothing like the way that these functions appear to work. It's called during the compilation process and the arguments it's called with is ASTs.

That said, at the end of the day, the consumer's experience is all that matters, so we need a version of the codegen function that works the way it's expected. So we'll define our types and then make sure that we cast the macro function like a regular function.

import { createMacro } from 'babel-plugin-macros'
import type { MacroHandler } from 'babel-plugin-macros'

const codegenMacro: MacroHandler = function codegenMacro(/* some args */) {
	// the implementation here is irrelevant
}

// use the `createMacro` utility to turn the codegenMacro into a babel macro
const macro = createMacro(codegenMacro)

Ok, so keep in mind that the macro function is not actually ever called by user code. This function will be called by babel-plugin-macros, and it'll be called with the MacroHandler arguments. However, as far as TypeScript is concerned, the developer will be calling it, so we need to give it the right type definitions and everyone will be happy. So let's define those:

// This handles the tagged template literal API:
declare function codegen(
	literals: TemplateStringsArray,
	...interpolations: Array<unknown>
): any

// this handles the function call API:
declare function codegen(code: string): any

// this handles the `codegen.require` API:
declare namespace codegen {
	function require(modulePath: string, ...args: Array<unknown>): any
}

// Unfortunately I couldn't figure out how to add TS support for the JSX form
// Something about the overload not being supported because codegen can't be all the things or whatever
// PRs welcome!

With those overloads defined, now we just need to force TypeScript to treat our macro file like the codegen function we've defined. We also need to make this the default export of our macro file, so we'll do all that at once:

export default macro as typeof codegen

You can peruse it all together in babel-plugin-codegen src/macro.ts file.

I hope that's useful! Good luck to yah!