Sub topic 7
noImplicitAny: no silent any
This chapter assumes you know basic TypeScript syntax (annotations, interfaces, functions) and have a tsconfig.json with "strict": true or are about to add one. The previous chapter showed that strict is an umbrella option. This chapter covers its most important member, noImplicitAny.
What the flag does
TypeScript uses the type any to switch off checking. A value of type any can be called, indexed, or assigned to anything, and the compiler reports nothing.
Without noImplicitAny, the compiler falls back to any whenever it cannot work out a type. It does this silently. With the flag on, those places become errors, so every any in your program is one you wrote yourself.
The flag does not ban any. It bans accidental any.
{
"compilerOptions": {
"strict": true
}
}"strict": true turns noImplicitAny on. You can also enable it alone with "noImplicitAny": true, which is useful in a migration (see the migration chapter).
The basic error
An unannotated function parameter has nothing to infer its type from, so it becomes any.
function double(x) {
return x * 2;
}
function doubleTyped(x: number): number {
return x * 2;
}With the flag on, the first function fails with error TS7006: Parameter 'x' implicitly has an 'any' type. The second compiles. Without the flag, double("abc") compiles and returns NaN at run time. With the flag, the mistake is caught where you wrote the function.
Where implicit any appears
The parameter case is the most common, but the compiler reports several others.
| Situation | Typical error code | Fix |
|---|---|---|
| Parameter without annotation | TS7006 | Annotate the parameter |
| Destructured parameter without annotation | TS7031 | Annotate the whole pattern |
| Indexing an object with a plain `string` | TS7053 | Use a `Record` type or a `keyof` type |
| Importing a module with no type declarations | TS7016 | Install `@types` or declare the module |
| Variable whose type cannot be determined in a closure | TS7034 | Annotate the variable |
Destructured parameters
Destructuring does not give types to the names it creates. Each name is reported separately.
interface Person {
name: string;
age: number;
}
function describe({ name, age }: Person): string {
return `${name} is ${age}`;
}
console.log(describe({ name: "Ada", age: 36 }));Without the : Person annotation, both name and age produce TS7031. Annotate the pattern as a whole, not each name.
Indexing with a string
This error surprises many people because the code looks harmless.
const prices = { apple: 1, pear: 2 };
function priceOf(name: string): number {
return prices[name];
}TypeScript reports TS7053: the expression of type string cannot index the type { apple: number; pear: number; }. The object has exactly two known keys, and an arbitrary string might be neither. There are two honest fixes. Pick the one that matches what you mean.
const prices: Record<string, number> = { apple: 1, pear: 2 };
function priceOf(name: string): number | undefined {
return prices[name];
}
const fixedPrices = { apple: 1, pear: 2 };
function fixedPriceOf(name: keyof typeof fixedPrices): number {
return fixedPrices[name];
}Use Record<string, number> when keys really are open-ended, as with a lookup table filled at run time. Use keyof typeof when the keys are a fixed set and callers should be forced to pick one of them. Notice that the first version returns number | undefined. Reading a missing key does give undefined, but TypeScript only knows this if noUncheckedIndexedAccess is on, which is covered in a later chapter.
Modules without types
If you import a JavaScript package that ships no type declarations, the import is implicitly any.
import legacy from "legacy-lib";This reports TS7016: could not find a declaration file for module legacy-lib. You have three options, in order of preference:
- Install the community types, usually
npm install --save-dev @types/legacy-lib. - Write a small declaration file with the parts you use.
- Declare the whole module as untyped, which is an explicit
anyfor that module.
declare module "legacy-lib";Put that line in a .d.ts file inside a folder covered by include. It silences the error but gives up checking for everything imported from that package. Treat it as a temporary measure and leave a comment saying why.
What does not trigger the error
The flag only fires when the compiler has to guess. It stays quiet when it can infer a type.
- Contextual typing. A callback passed to a typed function receives its types from that function. In
["a", "bb"].map(s => s.length),sis inferred asstring. - Initializers.
let count = 0infersnumber. - Control-flow typing of bare declarations.
let result;has an evolving type that follows your assignments. It only errors if the compiler cannot follow it, for example when a closure captures the variable (TS7034). - Explicit
any. Writingx: anyis allowed. You made that choice visibly. - Values that already are
any.JSON.parsereturnsanyin the standard library, soconst data = JSON.parse(text)is not an error. The flag detects only inferredany.
const words = ["alpha", "be"];
const lengths = words.map(w => w.length);
let found;
found = words.find(w => w.startsWith("a"));
console.log(lengths, found);This compiles under strict. The parameter w is contextually typed, and found is narrowed by assignment. Do not add annotations the compiler already knows. They add noise and can drift out of sync with the real type.
Choosing a fix
When you meet a TS7xxx error, work through the question below before you reach for any.
unknown is the safe counterpart of any. You can assign anything to it, but you cannot use it until you check what it is.
function parseAge(input: unknown): number {
if (typeof input === "number") {
return input;
}
if (typeof input === "string") {
const value = Number.parseInt(input, 10);
if (!Number.isNaN(value)) {
return value;
}
}
throw new Error("Not a valid age");
}
console.log(parseAge("42"));Common mistakes
- Adding
: anyto make errors disappear. The error vanishes and so does the checking. Preferunknown, or a real type. - Annotating every callback parameter. Contextual typing already covers them.
- Declaring a module as untyped and forgetting it. Search for
declare module "when you audit a project. - Assuming the flag covers
JSON.parseand similar APIs. It does not. Annotate the result or validate it yourself.
Exercise
The function function total(items) { return items.reduce((sum, n) => sum + n, 0); } fails under noImplicitAny. Which parameters does the compiler report, which fix would you write, and why does the callback in reduce need no annotation once items is typed?
Show answer
The compiler reports items (TS7006). The callback's sum and n are not flagged separately once items has a type, because they are contextually typed from reduce. Fix it with function total(items: number[]): number { return items.reduce((sum, n) => sum + n, 0); }. With items typed as number[], n is inferred as number and sum as number from the initial value 0, so no further annotations are needed.
Exercise
A colleague "fixes" a TS7053 error on config[key], where key is a string, by changing the line to (config as any)[key]. Name one downside, and give a better fix for each of two cases: the keys are open-ended, and the keys are a fixed set.
Show answer
The cast turns off all checking for that expression, so typos and wrong value types go undetected, and the result is any that spreads into later code. For open-ended keys, type config as Record<string, ValueType> and handle the possible missing value. For a fixed set of keys, type the parameter as keyof typeof config so callers can only pass valid keys.