When to explicitly type functions
Always type functions, or never type them unless? It depends! I suggest using implicit types most of the time, and typing library functions.
Here’s a click handler with implicit typing:
const handleClick = () => { alert('clicked');};The compiler accepts this code without an explicit return type because it can
evaluate the function and conclude that it can’t return anything. We call this
not-thing void:
const handleClick = (): void => { alert('clicked');};Would adding the type be an improvement? Most click handlers don’t return anything, so adding that information doesn’t clarify much.
Bug what about library functions? These benefit from explicit typing.
Consider this function that accepts a string of markdown and returns a React node with parsed HTML:
import { ReactNode } from 'react';import ReactMarkdown from 'react-markdown';
const renderMarkdown = (markdown: string): ReactNode => { return <ReactMarkdown>{markdown}</ReactMarkdown>;}My compiler makes me type the markdown argument, because ReactMarkdown’s
child must be a string, and it can’t be sure that markdown is a string unless
we say it is. But, I didn’t have to type the returned ReactNode; TypeScript
can infer that from the ReactMarkdown library because it is itself typed.
If it’s not required, why add it? I think the answer lies in how library functions differ from other kinds of functions. We write library functions to:
- Encapsulate logic
- Reuse
Typing the function’s inputs and outputs supports each of these goals. It teaches programmers what the inputs and outputs should be, which can be unclear in isolation. It makes the function more reusable because it’s easier to understand.
I think library functions in general should be over-communicated. It should be clear through as many channels as possible what they do and don’t do.
It also makes it just a bit harder to casually extend the library function
because you have to spell out the new types. An explicit return type freezes the
public contract: inputs in, ReactNode out.