Sub topic 10
Implicit any and untyped parameters
This chapter assumes you can run tsc, read the file, line, and code parts of a diagnostic, and write basic annotations and interfaces. It covers one family of errors: the ones the compiler reports when it cannot work out a type and would have to fall back to any.
What "implicit any" means
any is the type that turns checking off. A value of type any can be called, indexed, or assigned to anything, and the compiler reports nothing. An implicit any is one you never wrote. The compiler reached a place where it had no annotation and nothing to infer from, so it chose any itself.
Whether that is an error depends on the noImplicitAny option. It is on when "strict": true is set. With it off, an unannotated parameter silently becomes any. With it on, you get a diagnostic.
function greet(name) {
return "Hello, " + name;
}$ npx tsc --noEmit --pretty false
src/greet.ts(1,16): error TS7006: Parameter 'name' implicitly has an 'any' type.The location points at the parameter, not the function name. The message names the parameter, so you know what to annotate. The fix is to say what you mean:
function greet(name: string): string {
return "Hello, " + name;
}
console.log(greet("Ada"));Why the compiler could not infer it
TypeScript infers types from three sources: an initializer, a return expression, and context. Context means that the place where an expression appears dictates its type. A function parameter has none of these unless you supply one. The compiler does not look at how callers use the function, so it cannot infer name from greet("Ada").
This explains why some unannotated parameters are fine. When a function expression is passed where a function type is expected, the parameters take their types from that expected type. This is called contextual typing.
const names: string[] = ["ada", "alan"];
const lengths = names.map((n) => n.length);
console.log(lengths);n has no annotation, but map on a string[] expects a callback taking a string, so n is string. No error appears.
Contextual typing disappears when you move the function out of that position:
const names: string[] = ["ada", "alan"];
const toLength = (s) => s.length;
console.log(names.map(toLength));src/lengths.ts(3,21): error TS7006: Parameter 's' implicitly has an 'any' type.When toLength is declared, nothing says what s is. The error is reported on the declaration, not on the map call, even though the call is where you intended to use it. Fix it where it is declared: const toLength = (s: string) => s.length;.
flowchart TDMermaid diagrams must use the diagram fence, so here is the decision flow in the required form:
Related implicit any diagnostics
The same option produces several codes. They share a cause but show up in different syntax.
| Code | Message (shortened) | Typical trigger |
|---|---|---|
| TS7006 | Parameter 'x' implicitly has an 'any' type | Unannotated function parameter |
| TS7031 | Binding element 'x' implicitly has an 'any' type | Destructured parameter without a type |
| TS7005 | Variable 'x' implicitly has an 'any' type | Variable whose type cannot be determined |
| TS7034 | Variable 'x' implicitly has type 'any[]' in some locations | Empty array captured by a nested function |
| TS7053 | Element implicitly has an 'any' type because expression of type 'string' can't be used to index type | Indexing an object with a plain `string` key |
Destructured parameters
Destructuring does not create types. Each name pulled out of an untyped object is its own implicit any.
function area({ width, height }) {
return width * height;
}src/area.ts(1,17): error TS7031: Binding element 'width' implicitly has an 'any' type.
src/area.ts(1,24): error TS7031: Binding element 'height' implicitly has an 'any' type.One mistake produced two diagnostics. Fixing the parameter type clears both:
interface Size {
width: number;
height: number;
}
function area({ width, height }: Size): number {
return width * height;
}
console.log(area({ width: 3, height: 4 }));The annotation goes after the whole pattern, not on each name.
Empty arrays
const items = []; is allowed under noImplicitAny. The compiler tracks an "evolving" type that changes as you push values. That tracking breaks when a nested function uses the array, because the compiler cannot know when the calls happen. You then get TS7034 on the declaration and TS7005 on the use. Annotate the declaration, for example const items: number[] = [];.
Indexing with a string
const prices = { apple: 1, pear: 2 };
const key: string = "apple";
console.log(prices[key]);This reports TS7053, because string is wider than the two keys that exist. Either type the object as Record<string, number>, or narrow the key to keyof typeof prices. Which one is right depends on whether arbitrary keys are legitimate. Use Record for a lookup table, and keyof when the keys are a fixed set.
Choosing a fix
There are four honest fixes and one dishonest one.
- Annotate the parameter. This is the default and works when you know the type.
- Give it a default value.
function pad(text: string, width = 8)inferswidthasnumber. A default also makes the parameter optional. - Restore context. Annotate the variable that holds the function with a function type, and the parameters follow:
type Predicate = (value: number) => boolean;
const isEven: Predicate = (v) => v % 2 === 0;
console.log(isEven(4));- Use
unknownwhen the type truly is not known, then narrow before use.
function describe(value: unknown): string {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
return "other";
}
console.log(describe("ada"), describe(3.14159), describe(null));unknown accepts any value but allows nothing until you check it. any accepts any value and allows everything. That difference is why unknown is the safer choice at a boundary.
The dishonest fix is writing : any just to silence TS7006. The error disappears, but so does checking for every use of that parameter, and the loss spreads to anything the value flows into.
Turning the option on in an existing project
Enabling strict on a large untyped codebase can produce hundreds of TS7006 errors at once. You can enable the option by itself instead:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"noImplicitAny": true,
"noEmit": true
},
"include": ["src"]
}Work through the errors file by file. Many are triaged by the same rule: annotate the function at its declaration, and callers often stop erroring on their own. When a project has no strict setting and the option is off, these diagnostics never appear, so a clean build there says little about parameter types.
Common mistakes
- Annotating the call site instead of the declaration. The error is on the parameter, so the fix is there too.
- Expecting
greet("Ada")to teach the compiler thatnameis astring. Inference does not flow from callers into parameters. - Putting
anyon a destructured name, such as{ width: any }. That is a rename in JavaScript syntax, not a type annotation, so annotate the whole pattern. - Reaching for a type assertion on the parameter's uses instead of typing the parameter once.
Exercise
This code reports TS7006 on the parameter item at the declaration of format. Why does the same kind of arrow function inside prices.map((p) => p.toFixed(2)) not report an error, and what is the smallest change that fixes format without using any?
const prices: number[] = [1, 2];
const format = (item) => item.toFixed(2);
console.log(prices.map(format));
Show answer
The arrow function inside prices.map(...) is contextually typed: map expects a callback taking a number, so p is inferred as number. format is declared on its own, with no expected type, so item has no source for its type and becomes an implicit any. Annotate the parameter at the declaration: const format = (item: number) => item.toFixed(2);. Annotating the variable with a function type such as (item: number) => string would also work.
Exercise
A function receives data parsed from a request body and you do not yet know its shape. Which parameter type is safer, any or unknown, and what must you do before calling a string method on it?
Show answer
unknown is safer. It accepts any value but permits no operations until you narrow it. Check with typeof value === "string" (or another guard) first, and then value.toUpperCase() type-checks inside that branch.