Sub topic 3
Implicit Any, Modules, and Safe TypeScript Fixes
Assume you know JavaScript functions, objects, arrays, modules, and basic TypeScript annotations, interfaces, and unions.
Untyped parameters
With noImplicitAny enabled, TypeScript reports TS7006 when a parameter has no usable type and would otherwise become any. The any type disables most checking, so annotate the parameter or infer its type from context.
function greet(name: string): string {
return `Hello, ${name}`;
}
const names = ["Ada", "Linus"];
const messages = names.map((name) => greet(name));
console.log(messages);If the value can have different forms, describe that with a union and narrow it before using it.
function formatId(id: number | string): string {
if (typeof id === "number") {
return id.toString();
}
return id.trim();
}When a module cannot be found
TS2307 means the compiler cannot resolve an import. Check the module path, filename spelling, file extension conventions, package installation, and module and moduleResolution settings. Fix the module boundary before changing types inside the imported code.
Which error to fix first
Fix the earliest error in the dependency chain. A missing module or incorrectly typed declaration can cause many later errors. After each fix, run the compiler again. The remaining diagnostics are easier to interpret when cascading errors disappear.
Errors involving generics
A generic type uses a type parameter, such as Array<T>. Read the concrete type supplied for T, then check the operation that failed.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const value = first(["Ada", "Grace"]);
if (value !== undefined) {
console.log(value.length);
}Here, T becomes string, but first can still return undefined. The check narrows the result before property access.
Choose the right fix
- Fix the code when the value is genuinely wrong.
- Adjust the type when the declared contract is inaccurate.
- Fix the call site when it passes the wrong shape or value.
- Narrow a union or optional value when the value is valid but not yet proven safe.
Assertions and intentional failures
Use an assertion only when you have checked a fact that TypeScript cannot express. Use @ts-expect-error for a deliberate, tested error. It reports an error if the next line becomes valid, unlike @ts-ignore.
Keep errors out of merges
Run the compiler without emitting files in CI:
npx tsc --noEmit --pretty falseA nonzero exit status should fail the CI job, preventing type errors from returning to the main branch.
Exercise
What should you check first when one bad import produces many diagnostics?
Show answer
Fix the import or its module configuration first, then rerun the compiler to reveal the independent errors.