TypeScript errors are usually describing a mismatch between what your code can receive and what it is safe to do next. This guide gives you a repeatable workflow for reading compiler messages, narrowing union and nullable values, repairing generic constraints, handling object indexes and third-party packages, and choosing a precise fix instead of hiding the problem with any.
Overview
A TypeScript compiler error is a question about evidence. The compiler is asking whether it can prove that an operation is safe for every value represented by a type. For example, a value typed as string | number cannot be passed directly to a function that accepts only a string, because the number case has not been ruled out.
Before changing code, separate the message into three parts:
- The location: which expression or assignment failed?
- The expected type: what type does the receiving operation require?
- The actual type: what values does TypeScript believe may arrive?
Then ask what kind of correction is appropriate. The usual choices are a runtime check, a better type definition, a generic constraint, a function overload, a module declaration, or a type assertion supported by an established invariant. An assertion can be valid, but it should document knowledge that the compiler cannot derive—not replace missing validation.
When debugging, reproduce the error in the smallest useful example. Check the TypeScript version, the active tsconfig.json, imported declaration files, and whether the failing file is being compiled under the same settings as your editor. A red underline may reflect configuration or dependency changes rather than a defect in the expression itself.
Checklist by scenario
1. A union type will not accept the operation
Typical message: a property does not exist on type, or an argument of type A | B is not assignable to parameter of type A.
Narrow the value before using members that belong to only one branch. Prefer a discriminated union when you control the type:
type Result =
| { status: "ok"; value: string }
| { status: "error"; message: string };
function display(result: Result) {
if (result.status === "ok") {
return result.value;
}
return result.message;
}
A discriminant such as status gives both the compiler and future readers an explicit decision point. For built-in types, use guards such as typeof value === "string", Array.isArray(value), or value instanceof Date. For object shapes, use the in operator or a custom predicate.
2. A value may be null or undefined
Typical message: an object is possibly undefined or possibly null.
Decide whether absence is expected. If it is, handle it at the boundary:
function getLabel(user: { name?: string }) {
return user.name ?? "Unnamed user";
}
Use optional chaining when the whole operation can safely produce undefined, and use a guard when a missing value should follow a different path. Avoid non-null assertions such as value! unless the surrounding control flow or application invariant makes the value’s presence certain. If an API can omit a field, model that fact rather than forcing every caller to pretend it cannot happen.
3. Object indexing produces an implicit-any or missing-index error
Typical message: an expression of type string cannot be used to index a type.
TypeScript needs to know which keys are valid. If the set of keys is fixed, use keyof:
const prices = { basic: 10, team: 25 } as const;
type Plan = keyof typeof prices;
function priceFor(plan: Plan) {
return prices[plan];
}
If arbitrary keys are genuinely supported, declare an index signature or use a Record, but do so only when unknown keys have a defined meaning. A broad Record<string, unknown> is safer than Record<string, any> because it preserves the need to inspect values before using them.
4. A generic function is too permissive
Typical message: a type is not assignable to a constraint, or a property cannot be used on a generic type.
A type parameter does not automatically have every property. Add the smallest constraint that guarantees the operation:
function getId<T extends { id: string }>(item: T): string {
return item.id;
}
Do not add a constraint merely to silence an error. First identify what the function truly requires. If the function needs only an identifier, constrain it to an identifier rather than to a large application interface. If two inputs must share the same type, use one type parameter; if they can differ, use separate parameters. Also check whether inference is being weakened by an overly broad annotation at the call site.
5. Functions are not assignable to one another
Typical message: parameter types are incompatible, or a callback cannot be assigned to the expected function type.
Compare both parameter and return types. A callback that accepts only a specific subtype may not be safe where the caller can provide a broader type. Make the callback accept every value the caller promises to send, or narrow inside the callback. If a function has several legitimate calling forms, overload signatures can describe those forms while one implementation handles the runtime logic.
6. An imported package has missing or incompatible types
Typical message: no declaration file was found, a module has no exported member, or an imported value has an unexpected type.
Check the package’s installed version, its declared entry points, and whether the import matches the package’s documented module format. Inspect the resolved declaration file rather than guessing from runtime behavior. If a small internal module lacks declarations, write a local .d.ts file that describes the public surface you actually use. Keep that declaration narrow and mark uncertain values as unknown until they are validated.
What to double-check
- Compiler settings: confirm the file uses the intended project configuration. Strictness options, module resolution, target libraries, and included files can change diagnostics.
- Library types: verify that the selected runtime libraries include the APIs your code uses. A browser API and a server API may not be available under the same type configuration.
- Declaration versus runtime behavior: TypeScript checks declarations, while JavaScript executes values. A package may work at runtime but expose incomplete or incompatible declarations.
- Widening: inspect whether a literal such as
"open"has widened tostring. Use a precise annotation oras constwhere preserving the literal is meaningful. - Control-flow boundaries: narrowing may be lost after reassignment, across callbacks, or when a value is copied into a differently typed variable. Recheck the value near the operation that fails.
- Generated and cached files: restart the TypeScript language service or rebuild generated declarations when the editor and command-line compiler disagree.
When an error appears after a dependency upgrade, compare the lockfile and compiler configuration before rewriting application code. A changed declaration can expose an existing assumption, but it can also indicate an import or version-compatibility issue.
Common mistakes
Replacing the value with any. This removes useful checking from the entire path. Prefer unknown at untrusted boundaries and narrow it deliberately.
Adding an assertion before understanding the mismatch. value as User changes the compiler’s view without changing the runtime value. Use it only when validation happened elsewhere and that invariant is documented.
Making every property optional. Optional fields model real absence; they should not be used to avoid deciding which fields are required in a valid state. Consider separate types for loading, success, and error states.
Using a broad string index signature for a fixed object. This weakens typo detection. Use a key union when the valid keys are known.
Fixing only the error location. The best correction may be earlier: parse external data into a known shape, improve a function’s return type, or preserve a discriminant when constructing an object.
Ignoring the smallest reproduction. A reduced example often reveals that the real issue is an inferred type, an import path, or a configuration mismatch rather than the framework or feature being developed.
When to revisit
Return to this checklist whenever a TypeScript upgrade, framework migration, dependency refresh, strict-mode change, or refactor introduces new diagnostics. Revisit it during onboarding and before merging a large type-model change so that temporary assertions do not become permanent API design.
For each new error, record the original type, the operation that failed, and the fix category: narrow, validate, constrain, overload, declare, or redesign. Then run the project’s normal type-check and test commands rather than relying only on editor feedback. If the same error recurs, improve the shared type or boundary instead of applying another local assertion.
A practical final pass is:
- Read the complete diagnostic, including the final assignability detail.
- Inspect the inferred type at the failing expression.
- Confirm the active TypeScript configuration and dependency declarations.
- Choose the narrowest safe correction.
- Test both the expected case and the invalid or absent case that caused the uncertainty.
- Remove temporary logging, assertions, or broad types that are no longer needed.
TypeScript becomes easier to troubleshoot when errors are treated as information about a type boundary. The goal is not to make the compiler quiet; it is to make the program’s assumptions explicit enough that both the compiler and the next developer can verify them.