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





















