TypeScript?
TypeScript is described as a syntactic superset of JavaScript, . This means it includes all of JavaScript’s features and adds more on top
The main addition is static typing, which is presented as a way to prevent developers from making mistakes by catching errors during development that standard JavaScript would not alert you to
- It’s likened to having a buddy double-check your work
- TypeScript helps you avoid issues like passing a string where a number is expected or trying to access a property that doesn’t exist on an object
Installation and Config of TS
Installation
- Install TypeScript using npm in the terminal:
npm install typescript --save-dev
- Initialize a configuration file by typing
npx tsc --init
Configuration
This initialisation creates a tsconfig.json
file, . This file contains compiler options which are like customizable settings for the TypeScript compiler. Some of the options mentioned include:
- target: Specifies the JavaScript version that TypeScript will compile to TypeScript selects one automatically, but you can choose a modern version like es2020 or ES next
- module: Specifies the module system to use for JavaScript files, . The default is
commonjs
, which is common in Node.js and uses require for importing andmodule.exports
for exporting, . You can also use modern systems like es next or es6 with import and export syntax - esModuleInterop: Acts as a bridge to smooth out compatibility issues between different module systems
- forceConsistentCasingInFileNames: Ensures that import paths match the case of file names to prevent errors on case-sensitive file systems
- strict: Enables strict type checking, which is considered critical when using TypeScript
- skipLibCheck: Skips type checking for library files, speeding up compilation by assuming the library code is correct
Usage of TS
Type Safety
- A core function of TypeScript is ensuring type safety for variables. While in JavaScript a variable can easily change its type, TypeScript allows you to specify the expected type
let username:string = "Neo";
- This prevents unexpected behaviour if, for example, a user accidentally enters a phone number (string) into a field meant for a name (string) or enters the word “twenty” (string) into a field expecting a numerical discount (number)
- By specifying the type, TypeScript will flag anything else as an error, allowing you to handle it
- This works for various data types like strings, numbers, and booleans (true or false)
TS in Arrays
- TypeScript also applies to arrays, ensuring they contain values of a specific type
- You can secure an array to accept only string values by adding a string type followed by square brackets (string[])
- If you need an array to accept multiple different types, you can use a Union type
- A Union type uses the pipe | operator to combine types, allowing a variable or array to accept values of any of the combined types while still maintaining type safety
- For an array, you enclose the union type in parentheses and add square brackets afterward, like (string | number)[]
- Union types can also be used for regular variables, allowing them to accept values of different specified types, such as allowing a user ID variable to be either a numeric ID or a username string (number | string)
TS Functions
When working with functions, TypeScript allows you to specify the types for the parameters (inputs) and the return value (output)
- This prevents issues like passing incorrect types to a function or a function returning an unexpected type
- For example, in a loan calculation function expecting two number inputs and returning a number output, TypeScript annotations ensure only numbers are passed in and a number is returned
- You add the type annotation after the function signature to enforce the return type.
function calculateLoan (amount: number, rate: number):number {}
return (amount * rate) / 12;
}
TS Interfaces
Define the structure of objects, acting as a template,They ensure consistency across objects by specifying which fields must exist and their types.TypeScript raises an error if a required property is missing or an invalid one is added
- Optional Properties in Interfaces: Add a question mark (?) after a field name in an interface definition to make that field optional, Objects can then be created without including this optional field, and they will still be considered valid by TypeScript
interface Employee {
id: number;
name: string;
position?: string;
}
const employeeTwo: Employee = {
id: 102,
name: "John",
};
Type Aliases
Provide a new name for an existing type, They can be used to create more specific and meaningful names for primitive types like string, number, or boolean, improving code readability
type variableName = String;
let color: variableName;
- Literal Types with Type Aliases: Restrict a type alias to accept only specific predefined values (literal values), not just any value of the base type
- This is useful for working with a set of fixed options, such as user roles
('admin' | 'moderator' | 'user')
.
Enum
Define named constant values, They make code more readable and maintainable by providing descriptive names for a set of numeric or string values (e.g., subscription tiers like Free, Basic, Premium, or HTTP status codes like OK = 200, NotFound = 404)
Enums ensure consistency and help avoid typos
enum Subscription {
Free = "free",
Basic = "basic",
Premium = "premium"
}
let userSubscription: Subscription = Subscription.Premium;
let userTwoSubscription: Subscription = Subscription. Trial;
Generics
- A way to create reusable components (like functions or types) that can work with multiple data types without losing type safety
- A generic acts as a placeholder for a data type. For example, a generic function can ensure that the type of the argument passed to it is the same as the type of the value it returns, regardless of what that type is
1 function identity<T>(arg: T): T {
return arg,
3 }
4
5 let num = identity(5);
6 let str = identity"Hello, world!");
7 let bool = identity(true);
8
9 let num = "Five"; // string Type, Error