TypeScript Error Messages
Diagnose and resolve frequent TypeScript compiler errors including type mismatches, missing names, and missing properties.
TL;DR
- Resolve type mismatches by inspecting declared
interfaceor primitive types. - Fix missing name errors by importing identifiers with
importstatements. - Narrow union objects before accessing properties using the
inoperator.
Type Mismatch Diagnostics
Argument type mismatchResolve mismatched function argument types.
function setAge(age: number): void {
console.log(age);
}
// Error: setAge("25");
setAge(25);Missing interface propertyProvide all required fields in object literals.
interface User {
id: string;
name: string;
}
// Error: const u: User = { id: "u1" };
const u: User = { id: "u1", name: "Ada" };Literal union mismatchPass exact permitted union string values.
type Mode = "read" | "write";
function openFile(mode: Mode): void {}
// Error: const m = "read"; openFile(m);
const m: Mode = "read";
openFile(m);Return type mismatchAlign return value with function annotation.
function getStatus(): boolean {
// Error: return "true";
return true;
}Cannot Find Name Diagnostics
Missing module importImport identifier from its declaring module.
// Error: Cannot find name 'render'
import { render } from "./renderer";
render();Block scope visibilityReference variables within their declared block.
let score = 0;
if (true) {
score = 100;
}
console.log(score);Missing global definitionsInstall type definitions for runtime globals.
// For Node.js globals like process:
// npm i -D @types/node
console.log(process.env.NODE_ENV);Type import requirementExplicitly import referenced type interfaces.
import type { Config } from "./config";
const settings: Config = { debug: true };Property Does Not Exist
Discriminated union accessNarrow unions before accessing specific members.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function getRadius(s: Shape): number {
if (s.kind === "circle") {
return s.radius;
}
return 0;
}In operator existence checkTest for presence of property at runtime.
type Admin = { role: string; perms: string[] };
type Guest = { role: string };
function check(user: Admin | Guest): boolean {
if ("perms" in user) {
return user.perms.length > 0;
}
return false;
}Dynamic dictionary indexingDeclare index signature for dynamic access.
interface Dictionary {
[key: string]: number;
}
const scores: Dictionary = {};
scores["alpha"] = 10;Function Signature Diagnostics
Wrong argument countPass required number of positional arguments.
function multiply(a: number, b: number): number {
return a * b;
}
// Error: multiply(5);
multiply(5, 10);Async promise returnAnnotate async functions with Promise wrapper.
// Error: async function load(): string {}
async function load(): Promise<string> {
return "data";
}Non callable valueEnsure expressions are functions before call.
const handler: (() => void) | undefined = undefined;
// Error: handler();
handler?.();Void function return checkPrevent returning values from void functions.
function logMessage(msg: string): void {
console.log(msg);
// Avoid: return true;
}Type Assertion Solutions
Safe unknown narrowingNarrow unknown types using typeof conditions.
function processInput(val: unknown): string {
if (typeof val === "string") {
return val.trim();
}
return String(val);
}Satisfies validationValidate structure while preserving literals.
type Theme = Record<string, string>;
const theme = {
primary: "#0070f3",
secondary: "#ff0080"
} satisfies Theme;
console.log(theme.primary.toUpperCase());DOM type assertionAssert specific HTMLElement subtypes.
const input = document.getElementById("search") as
HTMLInputElement | null;
input?.focus();Double assertion escapeCast via unknown for incompatible conversions.
// Use with extreme caution only:
const raw: string = "42";
const val = raw as unknown as number;Tips
- Hover over red squigglies in your editor or run
tsc --prettyto read full diagnostic message traces with helpful suggestions. - Use the
satisfiesoperator to validate object structures against types without discarding specific inferred literal types or widening values.
Warnings
- Avoid using
anyoras anytype assertions to bypass compiler errors, as this destroys type safety throughout your application. - Suppressing diagnostics with
@ts-ignorecomments hides legitimate breaking changes during future dependency upgrades and compiler refactors.
In Practice
Diagnosing and fixing type mismatches and undefined property accesses across an API response handler.
- Define a strict interface representing expected API data.
- Replace unsafe direct property access with type narrowing.
- Handle optional and nullable fields with fallback defaults.
- Validate shapes cleanly without resorting to any assertions.
interface ApiResponse {
status: "success" | "error";
data?: {
userId: string;
metrics: number[];
};
}
function handleResponse(res: ApiResponse): string {
if (res.status !== "success") {
return "Operation failed";
}
if (!res.data) {
return "Missing response payload";
}
const count = res.data.metrics.length;
const id = res.data.userId;
return `User ${id} recorded ${count} entries`;
}FAQ
This error occurs when a variable, object property, or function parameter expects a number primitive but receives a string instead. Check where the data originates, convert the value explicitly using Number(val) or parseInt(), or update the declared type if the string is expected.
The compiler emits Cannot find name when an identifier is referenced without being declared in the current scope or imported from a module. Ensure you add an import declaration at the top of the file, check for spelling typos, or install @types definition packages for global variables.
This happens when accessing a property that is not defined in the type interface, or when accessing a member on a union type where only some members declare that property. Resolve it by updating the interface, narrowing unions using discriminant properties, or checking existence with the in operator.
TypeScript permits callback functions to ignore trailing parameters because JavaScript functions frequently discard extra arguments. However, if your callback declares more parameters than the caller supplies, or parameter types conflict, TypeScript emits an incompatible signature error.
Type assertions using as are appropriate only when you possess verified runtime domain knowledge that the compiler cannot infer, such as querying DOM elements or deserializing parsed payloads after runtime validation. Prefer type guards and unknown narrowing over unverified assertions.