TypeScript is a typed superset of JavaScript that adds static type definitions to your code to catch errors during development. It allows you to define the shape of your data using interfaces and types, ensuring that functions receive the correct inputs and return the expected outputs.
A common misconception is that TypeScript protects your code at runtime. In reality, TypeScript types are completely removed during compilation, meaning they only provide safety while you are writing the code, not while the application is running in the browser.
What are the Basic Type Annotations?
Basic types define the simplest building blocks of your data. You apply them using a colon after the variable name. Use string for text, number for all numeric values (including integers and floats), and boolean for true or false values. Since JavaScript does not distinguish between integers and decimals, TypeScript uses the single number type for both.
Arrays require a specific syntax to ensure every element in the list is of the same type. You can write this as type[] or Array<type>. For example, string[] ensures that only text can be added to the list. If you need a list that can hold multiple types, you use a union type, such as (string | number)[].
The any type is a fallback that disables type checking. While it allows you to bypass the compiler, using it too often removes the benefit of using TypeScript. A safer alternative is unknown. When a variable is unknown, TypeScript forces you to perform a type check or a type cast before you can perform operations on that value, which prevents runtime crashes.
How do Interfaces and Type Aliases Work?
Interfaces and type aliases both allow you to define the structure of an object. An interface is typically used to define the contract for an object or a class. You list the property names and their types inside curly braces. For example, a User interface might include a name: string and an id: number.
You can make properties optional by adding a question mark before the colon. An optional property like email?: string means the object can exist without an email address. This is useful for configuration objects where only some settings are required for the program to function.
Type aliases are created using the type keyword. While they look similar to interfaces, aliases can also define union types or primitive aliases. A union type allows a variable to be one of several types, written as string | number. This is helpful when a function might return a value or an error message.
Intersection types use the & symbol to combine multiple types into one. If you have a Person type and a Worker type, an intersection Person & Worker creates a new type that must satisfy the requirements of both. This allows you to compose complex data structures from smaller, reusable pieces.
How do you Type Functions and Parameters?
Typing a function involves defining the types of the arguments it accepts and the type of value it returns. The return type is placed after the parentheses. If a function does not return a value, use the void type. If a function is designed to never finish (such as one that throws an error or enters an infinite loop), use the never type.
Optional parameters are placed at the end of the argument list and marked with a question mark. Default parameters provide a fallback value if no argument is passed. When you provide a default value, TypeScript automatically infers the type of that parameter, so you do not need to write the type annotation explicitly.
Function overloads allow a single function to be called in different ways. You define multiple signatures for the function, and then provide one single implementation that handles all cases. This is useful when the return type depends on the type of the input provided.
What are Generics and How are They Used?
Generics allow you to create components that work over a variety of types rather than a single one. This provides flexibility while maintaining type safety. You define a generic using a type variable, usually denoted as <T>, placed before the function parentheses or class name.
A common example is a function that returns the first element of an array. Instead of using any[], you use <T>(args: T[]): T. This tells TypeScript that the return type will be exactly the same as the type of the elements in the input array. If you pass in a list of numbers, the return type is a number; if you pass in a list of strings, the return type is a string.
You can also constrain generics using the extends keyword. This limits the types that can be passed into the generic. For example, <T extends { length: number }> ensures that whatever type is used must have a length property, such as a string or an array. This allows you to access specific properties inside the generic function without causing a compiler error.
How do you Handle Type Casting and Assertions?
Type assertions are used when you know more about a value's type than TypeScript does. You can use the as keyword to tell the compiler to treat a variable as a specific type. This is common when working with DOM elements. For example, document.getElementById('myInput') as HTMLInputElement tells TypeScript that the element is specifically an input field, giving you access to the value property.
Avoid using type assertions to force a type when you are unsure. This bypasses the safety checks and can lead to runtime errors if the value is not actually what you claimed it to be. Instead, use type guards to verify the type at runtime.
Type guards are expressions that perform a runtime check to narrow down a type. The typeof operator is used for primitives, while the instanceof operator is used for classes. You can also create custom type guards by writing a function that returns a boolean and uses the is keyword in the return type, such as pet is Fish. This tells the compiler that if the function returns true, the variable is definitely of that specific type within that block of code.
How do you Configure the Compiler?
The tsconfig.json file controls how the TypeScript compiler behaves. One of the most important settings is strict. Enabling strict: true activates a suite of checks, including noImplicitAny and strictNullChecks. This forces you to be explicit about your types and handle potential null or undefined values.
The target setting determines which version of JavaScript the code is compiled into. If you are targeting older browsers, you might set this to ES5. For modern environments, ESNext or ES2020 is common. The module` setting defines the module system used, such as CommonJS for Node.js or ESNext for modern frontend bundles.
The outDir setting specifies where the compiled JavaScript files should be placed. Keeping your source .ts files in a src folder and your output .js files in a dist or build folder keeps your project organized and prevents the compiler from accidentally processing its own output.