Week-9.2 Typescript Intro
Week-9.2 Typescript Intro
Week 9.2
Introduction to Typescript
In this lecture, Harkirat offers a brief introduction to TypeScript , covering language classifications,
the importance of strong typing, and an overview of TypeScript's execution. The lecture includes
insights into the TypeScript compiler, implementing basic types, and understanding the distinctions
between Interfaces and Types
Introduction to Typescript
Types of Languages
Typescript
Why Typescript
What Typescript
How Typescript
https://app.100xdevs.com/pdf/186 1/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
2] Sum Function
2] rootDir:
3] outDir
4] noImplicitAny
5] removeComments
Interfaces
Understanding Interfaces
Assignment 1
Assignment 2
Implementing Interfaces
Types
Features
Interfaces vs Types
Major Differences
1. Declaration Syntax:
Other Differences
Examples
Types of Languages
https://app.100xdevs.com/pdf/186 2/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
2. Dynamic Type Changes: Variables can change types during execution, offering more adaptability.
This flexibility allows for a dynamic approach to variable assignments and operations.
3. Runtime Error Discovery: Type errors may be discovered during runtime, potentially leading to
unexpected behaviors. This characteristic provides more freedom but requires careful handling.
int main() {
int number = 10;
number = "text"; // Error: Cannot assign a string to an integer variable
return 0;
}
Explanation:
C++ is a statically-typed language, meaning variable types must be declared and are enforced at
compile-time.
In the given code, number is declared as an integer ( int ), and attempting to assign a string
("text") to it results in a compile-time error.
The type mismatch between the declared type and the assigned value leads to a compilation
failure.
2. Type Safety: The compiler or interpreter guarantees that operations are performed only on
compatible types. This ensures that type-related errors are caught early in the development
process.
https://app.100xdevs.com/pdf/186 3/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
3. Early Error Detection: Type errors are identified and addressed at compile-time, providing early
feedback to developers. This leads to increased reliability and reduces the likelihood of runtime
errors.
Explanation:
In the provided JavaScript code, number is initially assigned the value 10 (a number), and later, it
is assigned the value "text" (a string).
JavaScript allows this flexibility, and the code executes without type-related errors.
Considerations:
Statically-typed languages like C++ provide early error detection during compilation, ensuring
type consistency.
Dynamically-typed languages like JavaScript offer flexibility but may require careful handling to
avoid unexpected runtime errors.
The choice between strongly typed and loosely typed languages depends on
project requirements, developer preferences, and the balance between early
error detection and flexibility during development. Each type has its advantages
and considerations, influencing their suitability for specific use cases.
Typescript
Why Typescript
https://app.100xdevs.com/pdf/186 4/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
JavaScript is a powerful and widely used programming language, but it has a dynamic typing system,
which means variable types are determined at runtime. While dynamic typing provides flexibility, it
can lead to runtime errors that are challenging to catch during development.
What Typescript
In response to these challenges, Microsoft introduced TypeScript, a superset of JavaScript that adds
static typing to the language. TypeScript is designed to address some of the limitations of JavaScript
by providing developers with a more robust type system.
How Typescript
1. Static Typing:
TypeScript introduces static typing, allowing developers to declare the types of variables,
parameters, and return values at compile-time.
Static typing helps catch potential errors during development, offering a level of code
safety that may not be achievable in pure JavaScript.
TypeScript is a superset of JavaScript, meaning that any valid JavaScript code is also valid
TypeScript code.
Developers can gradually adopt TypeScript in existing JavaScript projects without the need
for a full rewrite.
https://app.100xdevs.com/pdf/186 5/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
3. Tooling Support:
TypeScript comes with a rich set of tools and features for development, including code
editors (like Visual Studio Code) with built-in TypeScript support.
The TypeScript compiler (tsc) translates TypeScript code into plain JavaScript, allowing it to
run in any JavaScript environment.
IDEs (Integrated Development Environments) that support TypeScript offer improved code
navigation, autocompletion, and better refactoring capabilities.
TypeScript introduces concepts like interfaces and type declarations, enabling developers
to define clear contracts for their code.
Interfaces help document the shape of objects, making it easier to understand and
maintain the code.
6. Compilation:
TypeScript code is transpiled to JavaScript during the compilation process, ensuring that
the resulting code is compatible with various JavaScript environments and browsers.
Overall, TypeScript provides developers with the benefits of static typing while
preserving the flexibility and features of JavaScript. It has gained popularity in
large-scale applications and projects where maintaining code quality and
catching errors early are crucial.
https://app.100xdevs.com/pdf/186 6/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Developers write TypeScript code using .ts or .tsx files, employing TypeScript's syntax
with features like static typing, interfaces, and type annotations.
The TypeScript Compiler ( tsc ) is a command-line tool that processes TypeScript code.
1. Compilation Process:
The TypeScript Compiler parses and analyzes the TypeScript code, checking for syntax
errors and type-related issues.
It generates equivalent JavaScript code, typically in one or more .js or .jsx files.
The output JavaScript code closely resembles the original TypeScript code but lacks
TypeScript-specific constructs like type annotations.
TypeScript features that aren't present in JavaScript (e.g., interfaces) are often transpiled or
emitted in a way that doesn't affect runtime behavior.
1. JavaScript Execution:
The generated JavaScript code can now be executed by any JavaScript runtime or browser.
Developers can include the resulting JavaScript files in HTML documents or use them in
Node.js environments.
1. Runtime Environment:
In the chosen runtime environment, the JavaScript code is interpreted or compiled by the
JavaScript engine (e.g., V8 in Chrome, SpiderMonkey in Firefox).
Just-in-time (JIT) compilation or interpretation occurs to convert the code into machine
code that the computer's processor can execute.
In browser environments, the JavaScript code, generated from TypeScript, may interact
with the Document Object Model (DOM) to manipulate web page structure and behavior.
https://app.100xdevs.com/pdf/186 7/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
It is a part of the official TypeScript distribution and can be installed using tools like npm.
Developers run tsc from the command line, specifying the TypeScript file(s) they want to
compile.
Configuration for the compilation process can be provided via a tsconfig.json file.
The compiler performs type checking, emits JavaScript files, and allows customization of
compilation options.
In addition to the TypeScript Compiler ( tsc ), several alternative tools have gained popularity for
their efficiency, speed, and additional features when transpiling TypeScript to JavaScript. Here are a
couple of noteworthy ones:
https://app.100xdevs.com/pdf/186 8/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
1. esbuild: a highly performant JavaScript bundler and minifier, but it also supports TypeScript.
This command installs TypeScript globally on your machine, allowing you to use the tsc command
anywhere.
mkdir node-app
cd node-app
npm init -y
npx tsc --init
These commands create a new directory ( node-app ), initialize a Node.js project with default settings
( npm init -y ), and then generate a tsconfig.json file using npx tsc --init .
// a.ts
const x: number = 1;
console.log(x);
tsc -b
The -b flag tells TypeScript to build the project based on the configuration in tsconfig.json . This
generates a JavaScript file ( index.js ) from the TypeScript source ( a.ts ).
https://app.100xdevs.com/pdf/186 9/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
// index.js
const x = 1;
console.log(x);
Note that the generated JavaScript file doesn't include TypeScript-specific code. It's standard
JavaScript without types.
// a.ts
let x: number = 1;
x = "harkirat";
console.log(x);
tsc -b
Upon compiling, TypeScript detects the type error ( x being assigned a string) and reports it in the
console. Additionally, no index.js file is generated due to the type error.
This example illustrates one of TypeScript's key benefits: catching type errors at
compile time. By providing static typing, TypeScript enhances code reliability
and helps identify potential issues before runtime. This is particularly valuable in
large codebases where early error detection can save time and prevent bugs.
1. Number:
https://app.100xdevs.com/pdf/186 10/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Example:
2. String:
Example:
3. Boolean:
Example:
4. Null:
Example:
5. Undefined:
Represents a variable that has been declared but not assigned a value.
Example:
Objective:
Task:
Write a TypeScript function named greet that takes a user's first name as an argument and logs a
greeting message to the console.
Function Signature:
Solution:
// Example Usage
greet("harkirat");
Explanation:
: void specifies that the function does not return any value.
Inside the function body, a console.log statement prints a greeting message to the
console.
https://app.100xdevs.com/pdf/186 12/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
The provided argument must be a string, aligning with the specified type in the function
definition.
2] Sum Function
Objective:
Task:
Write a TypeScript function named sum that takes two numbers as arguments and returns their sum.
Additionally, invoke the function with an example.
Function Signature:
Solution:
// Example Usage
console.log(sum(2, 3));
Explanation:
https://app.100xdevs.com/pdf/186 13/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
The sum function is declared with two parameters, a and b , both of type number.
Inside the function body, the sum of a and b is calculated using the + operator.
Objective:
Understand Type Inference in TypeScript.
Task:
Write a TypeScript function named isLegal that takes an age as a parameter and returns true if
the user is 18 or older, and false otherwise. Also, invoke the function with an example.
Function Signature:
Solution:
} else {
return false;
}
}
// Example Usage
console.log(isLegal(22)); // Output: true
Explanation:
Inside the function body, an if statement checks if the provided age is greater than 18.
Objective:
Learn to work with functions as parameters in TypeScript.
Task:
Write a TypeScript function named delayedCall that takes another function ( fn ) as input and
executes it after a delay of 1 second. Also, invoke the delayedCall function with an example.
https://app.100xdevs.com/pdf/186 15/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Function Signature:
Solution:
// Example Usage
delayedCall(function() {
console.log("hi there");
});
Explanation:
The delayedCall function is declared with a parameter fn of type function that takes no
arguments and returns void .
Inside the function body, setTimeout is used to delay the execution of the provided
function ( fn ) by 1000 milliseconds (1 second).
The provided function logs "hi there" to the console after a 1-second delay.
https://app.100xdevs.com/pdf/186 16/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Below are a bunch of options that you can change to change the compilation process in the
tsconfig.json file:
When target is set to "es5" , the TypeScript compiler generates code compatible with
ECMAScript 5, which is widely supported across browsers.
Example:
{
"compilerOptions": {
"target": "es5",
// Other options...
}
}
TypeScript Code:
Output:
"use strict";
var greet = function (name) { return "Hello, ".concat(name, "!"); };
https://app.100xdevs.com/pdf/186 17/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
When target is set to "es2020" , the TypeScript compiler generates code compatible with
ECMAScript 2020, incorporating the latest features.
Example:
{
"compilerOptions": {
"target": "es2020",
// Other options...
}
}
TypeScript Code:
Output:
"use strict";
const greet = (name) => `Hello, ${name}!`;
By setting the target option, you ensure that the generated JavaScript code
adheres to the specified ECMAScript version, allowing you to control the level of
compatibility and take advantage of the features available in newer ECMAScript
versions.
2] rootDir:
The rootDir option in a tsconfig.json file specifies the root directory where the TypeScript
compiler ( tsc ) should look for .ts files.
It is considered a good practice to set rootDir to the source folder ( src ), indicating the starting
point for TypeScript file discovery.
Example:
{
"compilerOptions": {
"rootDir": "src",
// Other options...
https://app.100xdevs.com/pdf/186 18/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
}
}
3] outDir
The outDir option defines the output directory where the TypeScript compiler will place the
generated .js files.
Example:
{
"compilerOptions": {
"outDir": "dist",
// Other options...
}
}
If rootDir is set to "src" and outDir is set to "dist" , the compiled files will
be placed in the dist folder, mirroring the structure of the src folder.
4] noImplicitAny
The noImplicitAny option in a tsconfig.json file determines whether TypeScript should issue
an error when it encounters a variable with an implicit any type.
{
"compilerOptions": {
"noImplicitAny": true,
// Other options...
}
}
Example:
https://app.100xdevs.com/pdf/186 19/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
{
"compilerOptions": {
"noImplicitAny": false,
// Other options...
}
}
5] removeComments
The removeComments option in a tsconfig.json file determines whether comments should be
included in the final JavaScript output.
{
"compilerOptions": {
"removeComments": true,
// Other options...
}
}
{
"compilerOptions": {
"removeComments": false,
// Other options...
}
}
https://app.100xdevs.com/pdf/186 20/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
These options provide flexibility and control over the compilation process,
allowing you to structure your project and handle type-related scenarios
according to your preferences.
Interfaces
In TypeScript, an interface is a way to define a contract for the shape of an object. It allows you to
specify the expected properties, their types, and whether they are optional or required. Interfaces are
powerful tools for enforcing a specific structure in your code.
Understanding Interfaces
Suppose you have an object representing a user:
const user = {
firstName: "harkirat",
lastName: "singh",
email: "email@gmail.com",
age: 21,
};
To assign a type to the user object using an interface, you can create an interface named User :
interface User {
firstName: string;
lastName: string;
email: string;
age: number;
}
Now, you can explicitly specify that the user object adheres to the User interface:
https://app.100xdevs.com/pdf/186 21/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Explanation:
Inside the interface, you define the expected properties ( firstName , lastName , email ,
age ) along with their types.
By stating const user: User , you are explicitly indicating that the user object must
adhere to the structure defined by the User interface.
If the user object deviates from the defined structure or misses any required property,
TypeScript will raise a compilation error.
Assignment 1
Problem: Create a function isLegal that returns true or false if a user is above 18. It takes a user as
an input.
Solution:
Code Explanation:
https://app.100xdevs.com/pdf/186 22/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
An interface "User" is defined to enforce the structure of a user object with properties: firstName,
lastName, email, and age.
The function "isLegal" takes a user object as input and checks if the user's age is greater than 18.
It returns true if the user is legal (age > 18) and false otherwise.
Assignment 2
Problem: Create a React component that takes todos as an input and renders them.
Solution:
// Create a React component 'Todo' that takes a 'todo' prop and renders it
function Todo({ todo }: TodoInput): JSX.Element {
return (
<div>
<h1>{todo.title}</h1>
<h2>{todo.description}</h2>
{/* Additional rendering logic can be added for other properties */}
</div>
);
}
Code Explanation:
An interface "TodoType" is defined to specify the structure of a todo with properties: title,
description, and done.
An interface "TodoInput" is defined to specify the input prop for the Todo component.
https://app.100xdevs.com/pdf/186 23/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
The React component "Todo" takes a prop "todo" of type "TodoType" and renders its properties
(title and description).
Implementing Interfaces
In TypeScript, you can implement interfaces using classes. This provides a way to define a blueprint
for the structure and behavior of a class. Let's take an example:
Assume you have a Person interface:
interface Person {
name: string;
age: number;
greet(phrase: string): void;
}
greet(phrase: string) {
console.log(`${phrase} ${this.name}`);
}
}
It has properties ( name and age ) matching the structure defined in the interface.
This approach is handy when creating various types of persons (like Manager,
CEO), ensuring they all adhere to the same interface contract. It maintains
consistency in the structure and behavior across different classes.
https://app.100xdevs.com/pdf/186 24/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Types
In TypeScript, types allow you to aggregate data together in a manner very similar to interfaces. They
provide a way to define the structure of an object, similar to how interfaces do. Here's an example:
type User = {
firstName: string;
lastName: string;
age: number;
};
Features
1. Unions:
Unions allow you to define a type that can be one of several types. This is useful when dealing
with values that could have different types. For instance, imagine you want to print the ID of a
user, which can be either a number or a string:
Unions provide flexibility in handling different types within a single type definition.
1. Intersection:
Intersections allow you to create a type that has every property of multiple types or interfaces. If
you have types like Employee and Manager , and you want to create a TeamLead type that
combines properties of both:
type Employee = {
name: string;
startDate: Date;
};
https://app.100xdevs.com/pdf/186 25/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
type Manager = {
name: string;
department: string;
};
Intersections provide a way to create a new type that inherits properties from multiple
existing types.
In summary, while types and interfaces are similar in defining object structures,
types in TypeScript offer additional features like unions and intersections,
making them more versatile in certain scenarios.
Interfaces vs Types
Major Differences
1. Declaration Syntax:
Type:
More flexible syntax, can represent primitive types, unions, intersections, and more.
Interface:
https://app.100xdevs.com/pdf/186 26/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Can't be merged; if you define another type with the same name, it will override the previous
one.
Interface:
Interface:
Other Differences
Type Overriding:
Types cannot be overridden or merged. Redefining a type with the same name replaces the
previous one.
Types are more lenient when dealing with object literal assignments.
Types are more versatile for creating complex types and reusable utility types.
https://app.100xdevs.com/pdf/186 27/29
8/16/24, 5:52 PM Take your development skills from 0 to 100 and join the 100xdevs community
Use Types:
Use Interfaces:
Examples
Type Example:
Interface Example:
interface Employee {
name: string;
startDate: Date;
}
interface Manager {
name: string;
department: string;
}
In summary, choose types for flexibility and advanced type features, and use
interfaces for object shapes, contracts, and class implementations, ensuring a
consistent and readable codebase.
https://app.100xdevs.com/pdf/186 29/29