liveBook · Manning

Type hints

As explained in Secrets of the JavaScript Ninja, Third Edition

Syntax attached to a TypeScript declaration or expression that explicitly specifies expected types and can supply information for type checking and inference.

JavaScript may accept an argument whose type produces a surprising result: adding 1 to "10" yields "101". A TypeScript type hint, or type annotation, states an expected type so the compiler can flag an incompatible call before it runs. For example, `const addOne = (x: number) => x + 1` rejects `addOne("10")`. An editor can also display the expected argument type while you work. section 1.3.1

Annotate where the type checker needs information or where an explicit contract helps:

  • Parameters: `const pluralize = (str: string, count: number) => count === 1 ? str : `${str}s``. Under `strict`, untyped parameters that implicitly become `any` cause an error. A function type such as `(str: string, count: number) => string` can instead supply the parameter types. section 2.1.2
  • Rest and default parameters: `...remainingNumbers: number[]` specifies an array of numbers. A default such as `action = "skulking"` lets TypeScript infer `string`; annotate `action: string | null = "skulking"` when null must also be allowed. section 5.5.1
  • Return values: TypeScript can infer a return type from the possible returned values. Add one after the parameter list, as in `(str: string): string => ...`, when you want the checker to enforce the intended result. section 5.5.2

An explicit return type catches a missing case

Consider `const numberSign = (num: number): "positive" | "negative" => { if (num > 0) return "positive"; if (num < 0) return "negative"; };`. The checker reports that the function can reach its end without returning: zero was not handled. Adding a zero return and including `"zero"` in the return type makes the contract match the behavior. section 5.5.2

For a complex object parameter, a named `interface` or `type` can keep the annotation readable. An annotation is not a runtime guard: the TypeScript compiler removes it when producing JavaScript. Use inference to avoid repetition, and explicit types where they clarify an expectation or expose a mistake. section 2.1.2 section 5.5.1

Listing 12.8 Using a replacer function to transform a string
const kebabCaseRegex = /-([a-z])/g; #A
const technique = "shadow-clone-jutsu";
const camelCase = technique.replace( #B
  kebabCaseRegex, #B
  (_, letter: string) => letter.toUpperCase(), #B
); #B

console.assert(
  camelCase === "shadowCloneJutsu",
  "The kebab-case string becomes 'shadowCloneJutsu'",
);

A regular-expression replacement callback annotates its captured `letter: string`. TypeScript cannot determine the number of capture groups from the regex, so this annotation supplies information it cannot infer for that argument. section 12.5

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through parameter, function and return annotations, inference, and implicit-any errors; clarifies that annotations do not perform runtime checks.
Examples
Uses a pluralizing function, a number-sign function missing its zero case, and a regular-expression replacement callback.
What it assumes
Assumes familiarity with JavaScript functions and arguments, while introducing TypeScript parameter and return annotations through examples.
What you can do after
Apply it via TypeScript annotations to check arguments and intended return values while relying on inference where it suffices.
How it connects
Connects type annotations to type inference, union types, interfaces, strict mode and function parameters.

Also explained in

Compare how 22 books explain type hints →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.