As a SharePoint developer, you should learn TypeScript, which is essential for developing SharePoint Framework (SPFx) solutions. TypeScript provides features such as type inference and strict type checking, which can help catch errors before the code is run. I have provided a list of TypeScript tutorials for beginners and advanced developers. If you are starting to learn Typescript, check out the beginner’s tutorial list. Check out the list of advanced Typescript tutorials if you are an advanced user who knows Typescript.
What is Typescript?
TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code.
The main feature that distinguishes TypeScript from JavaScript is its static type system. TypeScript introduces optional static typing to JavaScript, which can help developers catch errors early in the development process, improve code quality, and enhance the maintainability of large codebases.
Advantages of TypeScript
TypeScript is primarily used for developing large-scale applications where the codebase can become complex and difficult to manage. Here are a few advantages of Typescript.
- TypeScript helps developers by adding static typing to JavaScript. This feature allows them to specify types for variables and functions, catching errors during development.
- Developers find improved tooling a strong advantage. Features like autocompletion and type-checking make the coding process smoother and more efficient.
- TypeScript integrates seamlessly with existing JavaScript projects. Developers familiar with JavaScript can start using TypeScript without learning new programming fundamentals.
- TypeScript projects often have better documentation. The static types make the code easier to read and maintain.
- By providing type safety, TypeScript helps teams catch bugs early. This leads to more robust and reliable code. Additionally, these features build confidence in the final product.
- Teams find that using TypeScript makes codebases easier to scale. As the project grows, maintaining code becomes simpler, allowing for easier collaboration and fewer errors.
Set up the TypeScript Environment
As a developer, the next thing you should learn is how to set up the development environment for Typescript.
Setting up TypeScript requires a few steps: users need to install TypeScript, set up the tsconfig.json
file, and understand the compilation process from TypeScript to JavaScript.
Download and Installing TypeScript
To start using TypeScript, install Node.js first. It provides the environment to run the TypeScript compiler. After installing Node.js, open the terminal or command prompt.
Execute the following command to install TypeScript globally:
npm install -g typescript
This command uses Node Package Manager (NPM) to download TypeScript and makes it accessible from anywhere on the system.
To check if the installation was successful, type:
tsc --version
This should display the installed version of TypeScript if everything is set up correctly.
Install an IDE like Visual Studio Code
Visual Studio Code (VS Code) is a popular, open-source code editor developed by Microsoft that is widely used for TypeScript development due to its excellent TypeScript support.
Visual Studio Code is highly recommended for Typescript development. You can download it from the official website.
VS Code comes with an integrated TypeScript language service that is out-of-the-box, providing features such as IntelliSense, which offers smart code completions based on variable types, function definitions, and imported modules.
Another advantage of using VS Code for TypeScript development is its powerful debugging capabilities. VS Code includes a built-in debugger that allows developers to set breakpoints, step through code, inspect variables, and call stacks. This makes it easier to diagnose and fix issues in TypeScript applications.
Configure the tsconfig.json File
After installing TypeScript, create a tsconfig.json
file in the project directory. This file is crucial for setting compiler options and how the project treats TypeScript files.
Use the command for initialization:
tsc --init
This generates a default tsconfig.json file, which can be customized. Important settings include target
(for specifying the JavaScript version), module
(to set the module system), and outDir
(to define the directory for compiled JavaScript files).
This file contains compiler options and other settings. Here is what it looks like:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Understand the Compilation Process
TypeScript is a superset of JavaScript, but it needs to be compiled into JavaScript. This conversion is handled by the TypeScript compiler, translated from .ts
files into .js
files.
Run the command below to compile TypeScript:
tsc
This translates the code and produces JavaScript output in the specified directory. The watch
mode can be used to recompile automatically whenever .ts
files change, by using:
tsc --watch
Basic TypeScript Types
TypeScript offers a range of basic types to help developers reduce errors in their code. As a developer, you should understand these types for more efficient coding, fewer bugs, and more robust programs.
Primitive Types: String, Number, and Boolean
TypeScript includes primitive types like string, number, and boolean. The string type is used for textual data. For example, let userName: string = "Alice";
.
The number type is for all kinds of numeric values, like let userAge: number = 25;
. Boolean is for true or false values, such as:
let isLoggedIn: boolean = true;
These types ensure that values are used consistently, catching errors early during development.
The Any, Unknown, and Never Types
The any type can hold any value, providing flexibility. However, overusing it may bypass types, leading to potential errors:
let variable: any = 5; variable = "text";
The unknown type is safer, requiring type checking before use:
let input: unknown = "hello";
if (typeof input === "string") {
console.log(input.toUpperCase());
}
The never type is for functions that do not return, such as those that always throw an error or have an infinite loop.
Array and Tuple Types
Arrays in TypeScript store multiple values of the same type. The syntax is straightforward:
let fruits: string[] = ["apple", "banana"]
Tuples, on the other hand, hold a fixed number of elements of specific types: let tuple: [string, number] = ["age", 30];
. This ensures that the structure stays consistent, reducing errors due to unexpected data structures.
Enum and Literal Types
Enums represent a set of named constants. They make code readable and reduce potential errors:
enum Direction {
Up,
Down,
Left,
Right
}
Literal types allow setting a specific set of values to a variable: let answer: "yes" | "no" = "yes";
. This enforces the use of predefined values, enhancing code accuracy.
Type Assertions and Aliases
Type assertions let developers override TypeScript’s inferred type for a variable. It’s like telling TypeScript to trust the developer’s input:
let code: any = "123";
let employeeCode = <number>code;
Type aliases give a type a new name, shortening complex types and improving readability. For instance:
type User = {
name: string;
age: number;
};
These tools help organize code efficiently while preserving type safety.
Important Typescript Concepts
Here are some important concepts in Typescript, that you should know as a developer.
Interfaces
Interfaces in TypeScript define the structure of an object. They help in defining contracts within your code and ensuring that objects adhere to specific structures.
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "John", lastName: "Doe" };
console.log(greeter(user));
Classes
TypeScript supports object-oriented programming with classes. You can define classes with properties and methods.
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
console.log(greeter.greet());
Modules
Modules in TypeScript help in organizing code into reusable components. You can export and import modules using the export
and import
keywords.
// math.ts
export function add(x: number, y: number): number {
return x + y;
}
// app.ts
import { add } from "./math";
console.log(add(2, 3));
Generics
Generics allow you to create reusable components that work with any data type in Typescript. Here is an example.
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>(100);
Type Inference
TypeScript can infer the types of variables based on their values. This feature reduces the need for explicit type annotations.
let x = 3; // inferred as number
Type Aliases
Type aliases allow you to create a new name for a type. This is useful for simplifying complex type definitions.
type Point = {
x: number;
y: number;
};
let point: Point = { x: 10, y: 20 };
Union and Intersection Types
Union types allow a variable to hold multiple types, while intersection types combine multiple types into one.
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
type Person = {
name: string;
};
type Employee = Person & {
employeeId: number;
};
Decorators
Decorators are a powerful feature in TypeScript that allows you to modify the behavior of classes and their members. They are often used in frameworks like Angular.
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
TypeScript Keywords
TypeScript, being a superset of JavaScript, inherits many of its keywords while also introducing several new ones to support its unique features. These keywords are crucial in defining the structure, behavior, and type safety of TypeScript code. Below are some of the most important TypeScript keywords and their functions.
let and const
TypeScript, like modern JavaScript (ES6+), uses let
and const
for variable declarations. The let
keyword allows you to declare block-scoped variables, which helps prevent issues related to variable hoisting and scope leakage.
On the other hand, const
is used to declare constants, ensuring that the variable’s value cannot be reassigned after its initial assignment.
let count: number = 10;
const name: string = "Alice";
type and interface
TypeScript introduces the type
and interface
keywords to define custom types and interfaces. These constructs are essential for describing the shape and structure of objects, enabling type safety and code readability.
type
: Used to create type aliases, simplifying complex type definitions and making code more readable.
type Point = {
x: number;
y: number;
};
let p: Point = { x: 10, y: 20 };
interface
: Defines a contract for objects, specifying the properties and methods that an object must implement. Classes can extend and implement interfaces.
interface Person {
name: string;
age: number;
}
class Employee implements Person {
constructor(public name: string, public age: number, public position: string) {}
}
enum
The enum
keyword allows you to define a set of named constants, making code more readable and maintainable. Enums are particularly useful for representing a collection of related values, such as days of the week or states in a state machine.
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
readonly
The readonly keyword in Typescript is used to mark properties of an object as immutable. Once a property is defined as readonly
, its value cannot be changed after initialization. This is useful for creating immutable data structures and ensuring that certain properties remain constant throughout the program’s lifecycle.
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
}
let circle = new Circle(5);
// circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property.
abstract
The abstract keyword is used to define abstract classes and methods in Typescript. An abstract class cannot be instantiated directly and is intended to be subclassed. Abstract methods, defined within an abstract class, must be implemented by derived classes.
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("Moving...");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Bark!");
}
}
let dog = new Dog();
dog.makeSound(); // Output: Bark!
dog.move(); // Output: Moving...
namespace
The namespace keyword is used to organize code into logical groups, preventing name collisions and improving code modularity. Namespaces are particularly useful in large applications where multiple modules and libraries are used.
namespace Geometry {
export class Circle {
constructor(public radius: number) {}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
}
let circle = new Geometry.Circle(5);
console.log(circle.area()); // Output: 78.53981633974483
as
The as keyword in Typescript is used for type assertions, allowing developers to override TypeScript’s inferred type system. This is useful when you know more about the type of a variable than TypeScript can infer.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Here are some Typescript keyword tutorials:
- default Keyword in Typescript
- typeof Keyword in Typescript
- require Keyword in Typescript
- super Keyword in Typescript
- const Keyword in Typescript
- declare Keyword in Typescript
- override Keyword in Typescript
- is Keyword in Typescript
- this Keyword in Typescript
- type keyword in Typescript
Typescript Tutorials for Beginners and Experienced Developers
Now, here is the list of Typescript tutorials for beginners as well as for experienced developers.
- TypeScript Hello World Tutorial
- Typescript data types
- Typescript check type
- How to add a property to object in Typescript
- Typescript Keywords List
- TypeScript Non-null Assertion Operator
- TypeScript Enum vs Union Type
- TypeScript Switch Case Examples
- TypeScript for Loop with Examples
- Typescript compare strings for sorting
- How to compare two strings in typescript
- How to Split String By New Line in Typescript?
- How to Split String by Length in Typescript?
- How To Split String And Get Last Element In Typescript?
- How to Split String by Regex in TypeScript?
- TypeScript Split String Into Array
- Typescript split string by dot
- Typescript Split String
- Typescript split string multiple separators
- How to Convert String to Enum in Typescript?
- How to Convert String to Date in TypeScript?
- How to Convert String to Number in TypeScript?
- How to convert string to double in typescript
- Typescript string to boolean
- How to get string between 2 characters in Typescript
- How to get string after character in Typescript
- How to Get Key by Value from enum String in Typescript
- TypeScript Enum Reverse Mapping
- Typescript remove quotes from string
- Typescript replace all occurrences in string
- How to check if string contains only numbers in typescript
- Typescript convert string to keyof
- Typescript string capitalize first letter
- How to create a multiline string in typescript
- Typescript check if a string contains a substring
- How to check if string is empty in typescript
- How to Merge Two Objects in TypeScript?
- Typescript Array
- TypeScript Array filter() Method
- Typescript array find
- How to Loop Through Array in Typescript?
- How to Sort Array Alphabetically in Typescript?
- How to Convert Typescript Array to String With Separator
- How to Filter An Array with Multiple Conditions in TypeScript?
- How to Filter Empty Strings from an Array in TypeScript?
- How to Filter Duplicates from an Array in TypeScript?
- How to Remove Null Values from an Array in TypeScript?
- How to Merge Object Arrays Without Duplicates in TypeScript?
- Typescript Get Last Element of Array
- Typescript merge two arrays of objects
- Typescript sort array by date
- Typescript sort array of objects by date descending
- Sort array of objects in typescript
- Typescript reverse array
- Typescript filter array of objects
- How to push an object into an array in Typescript
- Typescript Date
- How to Add Days to Date in Typescript
- How to Format Date with Timezone in Typescript?
- How to Convert Date to UTC in Typescript?
- How to Subtract Days from Current Date in Typescript?
- How to Check If Date is Valid in Typescript?
- How to Check Date Less Than Today in Typescript?
- How to Get Week Number from Date in TypeScript?
- How to create date from year month day in Typescript?
- How to Get First and Last Day of Week in Typescript?
- How to Remove Time from Date in TypeScript?
- How to Calculate Date Difference in Days in Typescript?
- Get month day year from date in Typescript
- Typescript Date Format
- How to Convert Date to String Format dd/mm/yyyy in Typescript
- Typescript compare dates
- Typescript Merge Maps
- Typescript map array of objects
- TypeScript Dictionary vs Map
- Typescript Dictionary Tutorials
- How to initialize empty dictionary in Typescript?
- How to Convert a Dictionary to an Array in Typescript?
- How to Sort a TypeScript Dictionary by Value?
- How to Get First Element from a Typescript Dictionary?
- How to convert an array to a dictionary in Typescript?
- How to Convert Typescript Dictionary to String?
- How to find key by value in Typescript dictionary?
- How to filter a dictionary in Typescript?
- How to Find Dictionary Length in TypeScript?
- How to check if a key exists in a dictionary in typescript?
- How to Check if a Dictionary is Empty in TypeScript?
- How to Declare a Dictionary in TypeScript?
- How to Remove Key from a Dictionary in Typescript?
- How to Loop Through Dictionary in Typescript?
- How to check if value exists in dictionary in Typescript?
- How to get value from a dictionary in Typescript?
- ReferenceError fetch is not defined in Typescript