Common Types Of TypeScript Errors

TypeScript Errors

TypeScript is designed to detect as many potential runtime errors in compile time as possible. That is why you may encounter more errors than you normally would if your code was written in JavaScript. Read on to find out about TypeScript errors and what you can do to avoid them.

TypeScript Errors

There are two categories of errors in TypeScript you may come across most often: syntax and type errors.

Syntax Errors

Syntax errors occur when the compiler doesn’t understand your code because of incorrect syntax. As a result, it can’t properly convert your TypeScript code to JavaScript.

Not every syntax error prevents you from compiling your code completely. Depending on your settings and tooling, you may still get some JavaScript output. But there is a high chance it won’t be the result you are looking for.

Consider this example:

let let message: string = "LearnshareIT";
console.log(message);

When you compile it, the compiler will give you this error:

typescript.ts:1:9 - error TS1005: ',' expected.
1 let let message: string = "LearnshareIT";

This happens because you have added an expected let keyword when initializing the message variable. Despite this error, the compiler still produces a JavaScript file:

var let, message = "LearnshareIT";
console.log(message);

In fact, running this output does what you initially expect it to do without any issues:

LearnshareIT

This doesn’t mean you are always lucky like this. You should find and fix all the syntax errors so the compiler can generate the JavaScript code you intend it to be.

Type Errors

TypeScript calls itself “JavaScript with syntax for types”, indicating strong support for types. The ability to check and enforce types is the primary reason many developers choose TypeScript in the first place.

TypeScript is a superset of JavaScript. It supports object-oriented programming with many built-in features like the type system, classes, inheritance, namespaces, and interfaces.

While TypeScript code is compiled to JavaScript code eventually, what makes it easier to develop your applications in TypeScript is static typing. It allows the programmer to declare types of variables when writing code and check them at compile time.

This feature can prevent a whole host of errors. Without type checking, such as in the case of JavaScript, you can only catch those errors in run time.

The simplest type-related errors are when you declare one type for a variable but assign a value of another incompatible type to it:

let message: number;
message = "learnshareit";
console.log(message);

Output:

typescript.ts:2:1 - error TS2322: Type 'string' is not assignable to type 'number'.
2 message = "learnshareit";

In this example, you first tell TypeScript that message is a number variable. But in the next line, you assign a string to it.

Assignability

The example above represents one of the most frequent error messages you may see in TypeScript: “Type…is not assignable to type…”

The “assignable to” phrase means a type can be used in place of the other. The error above basically tells us that the string type isn’t an acceptable substitute for ‘number’.

This relationship between two types isn’t bidirectional. Think each type is a set of possible values you can assign to a variable. A type can be a subset of another. Type A being assignable to type B doesn’t necessarily mean B is assignable to A.

Type Shapes

In addition to type compatibility, TypeScript also checks whether properties are valid for a certain object when you access them. It makes sure the type of that object has such a property or method like that.

let message: string = "learnshareit";
console.log(message.length);
console.log(message.join(".com"));

Output:

typescript.ts:3:21 - error TS2339: Property 'join' does not exist on type 'string'.
3 console.log(message.join(".com"));

We can use the length property of the message variable because the string type supports it. However, there is no join() method for this type. During compile time, the compiler sees this and notices something isn’t right with the method.

TypeScript can also investigate properties of types with complex shapes, such as interfaces:

interface Site {
    domain: string;
  }
   
function welcome(site: Site) {
    return "Hello to" + site.name;
}

Output:

Property ‘name’ does not exist on type ‘Site’.

TypeScript knows that the site object type doesn’t have any property called name. When you try to access it, the compiler will throw an error.

Other Error Types

In addition to common syntax and type errors, there are also other mistakes you can make when writing TypeScript code. For instance, the compiler will throw an error when you refer to a name that hasn’t been declared or initialized:

console.log(notValidName);

Output:

typescript.ts:1:13 - error TS2304: Cannot find name 'notValidName'.

Some other errors can only be detected at run time, such as RangeError:

console.log.apply(console, new Array(10000000000));

Output:

RangeError: Invalid array length

It has nothing to do with the TypeScript compiler, however. It is the JavaScript runtime that executes and produces this error when there is an array with an invalid length.

Stop Compiling If There Are Errors

Even when there are errors in your TypeScript code, the default setting of the compiler always forces it to make the best effort to compile it to JavaScript. Open your output, and you can see the contents getting updated. Sometimes, it looks basically the same as your TypeScript code.

This behavior comes from one of the philosophies of TypeScript. It assumes you know what you are doing, and much better than itself. The compiler throws out errors as warnings and doesn’t try to get in your way.

There are scenarios, however, where you want TypeScript to be stricter about the error and doesn’t produce any output when there are errors. You can use the –noEmitOnError option for this purpose.

tsc –noEmitOnError index.ts

By default, this compiler option is turned off to make it easier for you to watch changes in results when you iron out the errors.

Error Handling

For runtime errors, you can use the try-catch statements to handle them. It looks and works in the exact same way as JavaScript. There is a try block and at least a catch or finally block, or both:

try {
	throw 42;
} catch (exception)  {
	console.log(exception);
}

This example throws an exception (42), and the catch statement successfully catches it, executing the code block inside it.

Common Error

Summary

Besides errors that would also happen if you write your code in JavaScript, the type system of TypeScript also issues other type-related warnings during compile time. They are one of the most common TypeScript errors you will run into when developing your applications in this programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *