Common errors
The type errors you meet first (TS2304, TS2322, TS18048, TS7006, TS2339, TS2451) and run-time errors.
Runs in Zerethon IDE · TypeScript 7
Official TypeScript documentation ↗
TS2304: Cannot find name 'x'— a typo, or a variable declared elsewhere (or a missing import).TS2322: Type 'string' is not assignable to type 'number'— the value does not match the declared type; convert it (Number(text)) or fix the type.TS2345: Argument of type … is not assignable to parameter of type …— the same for a function argument.TS18048: 'x' is possibly 'undefined'— check first:if (x !== undefined),x ?? fallback, orx?.name.TS2451: Cannot redeclare block-scoped variable 'name'— a file withoutimport/exportis a script, and its top-level names are global: they clash with the same name in another script file, or with a built-in global such asname. Rename the variable, or addexport {};to make the file a module.TS7006: Parameter 'x' implicitly has an 'any' type— add a type to the parameter.TS2339: Property 'name' does not exist on type …— a typo, or the type does not declare that field.- Run-time errors (
TypeError,RangeError, …) are JavaScript errors; the stack trace names the.tsfile and line.
main.ts
function parsePort(text: string): number | undefined {
const port = Number(text);
return Number.isInteger(port) ? port : undefined;
}
const port = parsePort('80x');
// port + 1 would be TS18048: 'port' is possibly 'undefined'.
console.log(port === undefined ? 'invalid port' : port + 1);
console.log(parsePort('8080') ?? 'invalid port');
Output
invalid port 8080