Sub topic 7
noImplicitAny: no silent `any`
Assume you know basic TypeScript annotations, functions, and how to run npx tsc. This chapter focuses on one compiler option: noImplicitAny.
What implicit `any` means
any is a TypeScript type that disables most type checking. An implicit any happens when TypeScript cannot determine a type and silently assigns any to a value.
For example, the parameter x has no annotation:
// noImplicitAny reports an error on x.
function double(x) {
return x * 2;
}With noImplicitAny enabled, TypeScript reports:
Parameter 'x' implicitly has an 'any' type.The compiler is asking you to state the function's contract:
function doubleTyped(x: number): number {
return x * 2;
}
console.log(doubleTyped(21));The parameter must be a number, and the function returns a number. Callers now receive an error if they pass the wrong kind of value.
Enabling the check
Add the option to tsconfig.json:
{
"compilerOptions": {
"strict": false,
"noImplicitAny": true,
"target": "ES2022",
"module": "NodeNext"
},
"include": ["src"]
}In a new project, prefer "strict": true. The strict option is an umbrella setting that enables noImplicitAny along with several other checks:
{
"compilerOptions": {
"strict": true
}
}You can still set noImplicitAny explicitly when documenting or temporarily adjusting a project configuration.
Where errors appear
The most common errors involve parameters. They can also appear in declarations whose types cannot be inferred:
function formatUser(name, age) {
return `${name} is ${age} years old`;
}Annotate every parameter:
function formatUser(name: string, age: number): string {
return `${name} is ${age} years old`;
}
console.log(formatUser("Mina", 31));TypeScript does not require annotations everywhere. It can infer local variable types from initial values:
const count = 3;
const label = "ready";Here, count is inferred as a number and label as a string.
Contextual typing also supplies types when a value is used where a type is already known:
const names: string[] = ["Mina", "Leo"];
const upperNames = names.map((name) => name.toUpperCase());
console.log(upperNames);Because map is operating on a string[], TypeScript knows that name is a string.
Choosing an explicit type
Do not silence an error by adding any unless you have a specific boundary that cannot yet be typed. Prefer a precise type, a generic type, or unknown.
The compiler's model is straightforward:
Common mistake
Adding : any makes the error disappear but removes the protection:
function doubleUnchecked(x: any): any {
return x * 2;
}Use number when the function requires a number. If the input genuinely has an unknown shape, use unknown and narrow it before using it.
Exercise
What type should you add to the parameter in function greet(name) { return "Hi " + name; } if the function requires a text name?
Show answer
Add name: string, and usually declare the return type as : string: function greet(name: string): string { return "Hi " + name; }.