In TypeScript, how do you annotate a variable of a custom type?

Using TypeScript Type Annotation for Custom Types

In TypeScript, to define a variable of a custom type, you use the annotation by specifying the type after the variable name. This approach allows TypeScript to understand the type of variable you're working with so that it can offer better intellisense, type checking, and other benefits.

type CustomType = { property: string };

let variable: CustomType;

In the example above, we define CustomType as an object type with a property of type string, and variable is annotated to be of CustomType.

This TypeScript feature is powerful since it brings static typing to JavaScript and helps with checking type correctness at compile time. For instance, if you attempt to assign a number to variable typed as CustomType, TypeScript will raise a compilation error.

let invalid: CustomType = 123; // Error: Type '123' is not assignable to type 'CustomType'.

Remember, the type annotation adds clarity to your code which makes it more readable and maintainable for other developers or even yourself in the future. However, it also extends the amount of code written. Therefore, it's often considered best practice to use type annotations where explicit types are required or where type inference might not provide the level of precision you need.

You can even create complex custom types incorporating primitives, arrays, unions, intersections, and more, demonstrating TypeScript's versatility. Keep in mind, TypeScript aims to enhance the capabilities of JavaScript without disrupting the actual structure and syntax, therefore it seamlessly introduces type checking into a dynamically typed language like JavaScript.

By understanding and using type annotations effectively, you can avoid runtime errors, improve code quality, and create robust applications with TypeScript.

Do you find this helpful?