TypeScript
Strong typing :
*TypeScript helps catch errors at compile-time, reducing the chances of runtime errors.
\\ String\\
let mgs : String = "hello";
console.log( mgs );
output:
helloo
\\ number \\
let num : number = 1,2,3,4,5;
console.log( num );
output:
1,2,3,4
\\ boolean \\\
let bool : boolean = true ;
console.log( bool );
output:
true
\\ null \\\ -
null
represents the intentional absence of any object value.let value = null ;
console.log( typeof value );
output:
object
\\ undefined \\\
let value ;
console.log( type of value)
output:
undefine
Type Assignment:
Type Assignment:
* When creating a variable,
* There are two main ways TypeScript assigns a type:
- Explicit
- Implicit
In both examples below firstName is of type string:
Explicit Type:
Explicit :
- writing out the type:
example:
let firstName: string = "Dylan";
- Explicit type assignment are easier to read and more intentional.
Implicit type :
Implicit:
- Implicit assignment forces TypeScript to infer the value.
- Implicit type assignment are shorter, faster to type, and often used when developing and testing.
example:
let firstName = "Dylan";
Special types :
Type :any
any is a type that disables type checking and effectively allows all types to be used.
any
can be a useful way to get past errors since it disables type checking
example: for not using any type
let num : number ="hi"; // Type 'string' is not assignable to type 'number'.
console.log( num );
example: for using any type:
let num : any ="hi";
console.log( num ); // no error as it can be "any" type
Type : unknow
unknown
is a similar, but safer alternative toany
.
example:
let userInput: unknown;
let userId : unknown;
userInput =" jai ";
userId = 90;
console.log( typeof (userInput )," " + typeof ( userId));
output :
"String" , number
Array []:
- TypeScript arrays are used to store multiple values in a single variable.
example:
//array declare
let array : number [] = [ 1,2,4,5,7,7,9];
console.log( array );
output :
[ 1,2,3,4,5,7,7,9]
Type Inferred type :
- TypeScript has a feature called type inference
- It means that it can automatically determine the type of a variable based on the value you assign to it.
example:
// TypeScript infers the type as number
var myage = 20;
console.log(typeof myage);
// TypeScript infers the type as string
var myname = 'ram';
console.log(typeof myname);
// TypeScript infers the type as boolean
var bool = true ;
console.log( typeof bool);
output :
"String" , number, boolean
Type : Tuples:
- A tuple is a special type of array that can hold a fixed number of elements with specific types.
Example Explanation:
- Define a Tuple: You specify the types of each element in the tuple.
- Access Elements: You can access elements using their index, similar to arrays.
- Modify Elements: You can modify elements but must ensure the new value matches the specified type.
Define a Tuple:
example:
// Define a tuple with a string and a number
let person: [string, number];
person = ["ram",21]; // Initialize the tuple
console.log( person );
output:
[ 'ram', 21 ]
Access Elements:
example:
// Define a tuple with a string and a number
let person: [string, number];
person = ["ram",21]; // Initialize the tuple
console.log( person );
// Access elements in the tuple
console.log(person[0]); // Output: John
console.log(person[1]); // Output: 25
output:
ram
21
Modify Elements:
example:
// Modify elements in the tuple
person[0] = "Jane";
person[1] = 30;
// Access modified elements
console.log(person[0]); // Output: Jane
console.log(person[1]); // Output: 30
output:
jane
30
Readonly Tuple:
Simple Explanation
A Readonly Tuple is like a locked container where you can see what's inside, but you can't change its contents.
You can't modify the values.
only value can readonly.
example: ( only value can readonly. )
let readonlytuble : readonly [ string , number ];
readonlytuble = ["hello", 40]; // Valid: You can read the values
console.log( readonlytuble );
output:
hello
40
example: ( You can't modify the values. )
let readonlytuble : readonly [ string , number ];
readonlytuble = ["hello", 40]
console.log( readonlytuble );
readonlytuble[0]="hi" //Cannot assign to '0' because it is a read-only property.
readonlytuble[1]=50; //Cannot assign to '1' because it is a read-only property.
console.log(readonlyTuple[0]); // Output: 1
console.log(readonlyTuple[1]); // Output: Hello
output:
'readonlytuble' is declared here.
TypeScript Object Types:
- In TypeScript, an object is a collection of key-value pairs.
- You can define the structure of an object using interfaces or types to ensure type safety.
- Define an Interface: Use the
interface
keyword to create an interface with specific properties and methods. - Define a Type Alias: Use the
type
keyword to create a new type alias.
example:
//object
// Define an interface for a person object
type person = {
name :String;
age : number;
isStudent: boolean;
};
// Create an object that matches the Person interface
let person : person = {
name: "Alice",
age: 25,
isStudent: true
};
// Access properties of the object
console.log( person );
console.log( person.name );
console.log( person.age );
console.log( person .isStudent);
output:
{ name: 'Alice', age: 25, isStudent: true }
Alice
25
true
Optional Properties :
- In TypeScript, optional properties are properties that may or may not be present in an object.
- You define optional properties in an interface by using a question mark (
?
) after the property name.
example:
interface emp {
emp_id ? : string | number; // Optional property ( ? )
empname : string;
age : number
}
let emp : emp ={
emp_id : 1 , // Optional property
empname : "redy",
age : 34
}
console.log(emp);
console.log(emp.emp_id);
console.log(emp.empname);
output:
{ emp_id: 1, empname: 'redy', age: 34 }
1
redy
TypeScript Enums :
- An enum (short for "enumeration") is a way to define a set of named constants.
enum direction {
north,
east,
west,
south,
}
console.log( direction );
output:
{
'0': 'north',
'1': 'east',
'2': 'west',
'3': 'south',
north: 0,
east: 1,
west: 2,
south: 3
}
Numeric Enums - Initialized
- You can set the value of the first numeric enum and have it auto increment from that:
example:
enum CardinalDirections {
North = 1,
East,
South,
West
}
// logs 1
console.log(CardinalDirections.North);
// logs 4
console.log(CardinalDirections.West);
output :
1
4
Numeric Enums - Fully Initialized:
- You can assign unique number values for each enum value.
- Then the values will not incremented automatically:
example:
enum StatusCodes {
NotFound = 404,
Success = 200,
Accepted = 202,
BadRequest = 400
}
// logs 404
console.log(StatusCodes.NotFound);
// logs 200
console.log(StatusCodes.Success);
String Enums:
- Enums can also contain
strings
. - This is more common than numeric enums, because of their readability and intent.
enum CardinalDirections {
North = 'North',
East = "East",
South = "South",
West = "West"
};
// logs "North"
console.log(CardinalDirections.North); // North
// logs "West"
console.log(CardinalDirections.West); // west
TypeScript Type Aliases and Interfaces:
Type Aliases :
- Type Aliases allow defining types with a custom name (an Alias).
- Type Aliases can be used for primitives like
string
or more complex types such asobjects
andarrays.
example:
// Try creating a new Car using the alias provided
type CarYear = number;
type CarType = string;
type CarModel = string;
type Car = {
year: CarYear,
type: CarType,
model: CarModel
};
const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla"
const car: Car = {
year: carYear,
type: carType,
model: carModel
};
console.log(car);
output:
{ year: 2001, type: 'Toyota', model: 'Corolla' }
Interfaces
- Interfaces are similar to type aliases, except they only apply to
object
types.
// Define an interface for a person object
// type person = {
// name :String;
// age : number;
// isStudent: boolean;
};
TypeScript Union Types :
- Union types are used when a value can be more than a single type.
- Such as when a property would be
string
ornumber
.
Union | (OR)
- Using the
|
we are saying our parameter is astring
ornumber
.
let value: number | string;
value = 42; // This is fine
console.log(value); // Output: 42
value = "hello"; // This is also fine
console.log(value); // Output: hello
// value = true; // This would cause an error because
'true' is not a number or a string
output :
42,hello.
TypeScript Functions:
- function types are used to describe the types of functions, including their parameters and return types.
Return Type:
- The type of the value returned by the function can be explicitly defined.
example:
// Function that returns a string
function greet(name: string): string {
return "Hello, " + name;
}
// Call the function with an argument and log the resultconst message = greet (" kumar ")
console.log(message)
);
output:
hello kumar
Parameters:
- A parameter type specifies what type of value can be passed to a function's parameter.
function add ( a : number , b : number):number {
return a + b;
};
const result = add (100,20)
console.log( result);
output:
120
Optional Parameters:
- An optional parameter is a parameter you can choose to provide or leave out when calling a function.
- you make a parameter optional by adding a question mark (
?
) after its name.
interface person {
person_id :number;
person_name: String ;
person_dep :string;
person_age?:number
}
let person : person ={
person_id : 10,
person_name: "ram",
person_dep : "mca"
// person_age?:number Optional Parameters
}
console.log( person );
output:
{ person_id: 10, person_name: 'ram', person_dep: 'mca' }
Default Parameters:
- Default parameters in TypeScript allow you to set a default value for a parameter in a function.
example:
function details ( firstName : string ,lastName : string, age : number ) {
console.log( (firstName) +(lastName) +( age) );
}
details ("ram","kumar",20);
output:
ramkumar20
TypeScript Casting:
- Casting is the process of overriding a type.
- //only convent the type can't change value
// casting
//unknown String to String
let x: unknown ="hello";
console.log((x as string ).length)
console.log((<string>x ).length)
//unknown number to String
let y: unknown = 20; //only convent the type can't change value
console.log( (y as string).length);
output :
5
5
TypeScript Classes:
- A TypeScript class is a blueprint for creating objects with properties (variables) and methods.
- It's a way to define a template for creating multiple objects with the same structure and behavior.
example :
//simple class
class user {
id:number
constructor( a: number ) {
this.id = a
}
}
let userobject = new user ( 90 )
console.log( userobject.id); /// output = 90
Interface & implements
// interface & implements start
interface PersonInterface {
name: string; // Property name of type string
id: number; // Property id of type number
}
class Person implements PersonInterface {
name: string; // Property name of type string
id: number; // Property id of type number
constructor(name: string, id: number) {
this.name = name; // Initialize the name property
this.id = id; // Initialize the id property
}
}
let Personinter = new Person('John',1001); // Create a new Person object
console.log(Personinter); // Log the person object to the console
//output
//Person { name: 'John', id: 1001 }
// interface & implements end
Interface & implements multiple interance
// interface & implements start multiple interance
interface PersonInterface {
name: string; // Property name of type string
id: number; // Property id of type number
}
interface addressinterface {
city : string,
pincode: number
}
class Person implements PersonInterface, addressinterface {
name: string; // Property name of type string
id: number; // Property id of type number
city: string;// Property city of type number
pincode: number; // Property pincode of type number
constructor(name: string, id: number, city : string , pincode : number) {
this.name = name; // Initialize the name property
this.id = id; // Initialize the id property
this.city = city; // Initialize the id property
this.pincode = pincode; // Initialize the id property
}
}
let Personinter = new Person('John',1001,'chennai',235223);
// Create a new Person object
console.log(Personinter); // Log the person object to the console
//Person { name: 'John', id: 1001, city: 'chennai', pincode: 235223 }
Members: Visibility or Data modifiers :
- Data modifiers are keywords used to control the accessibility of class members (properties and methods).
- The three main data modifiers are
public
,private
, andprotected
.
class person {
private name: string;
constructor(name : string){
this.name =name
}
}
let personobjects = new person ("kumar");
personobjects.name
class empolyee extends person {
changeName = ( name : string)=>{
this.name = name
}
}
let personobject = new empolyee ("kumar");
personobject.changeName
TypeScript Basic Generics:
Normal type:
// Define a function named 'toArray' that takes two numbers as arguments
const toArray = (x: number, y: number) => {
// The function returns an array containing the two numbers
return [x, y];
}
// Call the 'toArray' function with the numbers 10 and 30
let newArray = toArray(10, 30);
// Print the resulting array to the console
console.log(newArray); // Output: [10, 30]
Generics type:
- TypeScript allow you to create functions, classes, or interfaces that can work with different data types.
- They make your code more flexible and reusable by letting you define a placeholder for a type.
//Generics
const arraygenerice = < S , N >(a:S ,b:N) => {
return [a ,b];
}
let newgenerice = arraygenerice (50 ,50 )
console.log( newgenerice); //[ 50 , 50 ]
multiples type:
// multiple types
let printValue = <x,y,z> (a:x ,b:y, c:z)=>{
console.log( typeof a ,typeof b,typeof c );
}
printValue( 1 ,'one',true)
/// number, string , boolean
TypeScript Conditional statements:
If Statement
- If Statement ts
// if condition ts
let age: number = 18
if (age < 10 ){
console.log( "voteing");
}
/// output is Voteing
- If Statement js
var age = 18;
if (age < 10) {
console.log("voteing");
}
/// output is Voteing
If-Else Statement:
- If-Else Statement ts
let age: number = 18
if (age < 10 ){
console.log( "voteing");
}
else{
console.log( "not voteing");
}
///output is not voteing
- If-Else Statement js
var age = 18;
if (age < 20) {
console.log("voteing");
}
else {
console.log("not voteing");
}
// voteing
If-Else If-Else Statement
- If-Else Statement ts
// if else if else
let colour : string = " yellow";
if ( colour == "red"){
console.log( " stop the car ");
}
else if ( colour == "green"){
console.log( " go ");
}
else if ( colour == "yellow"){
console.log( " get ready foe the car ");
}
else{
console.log( "there is no colour ");
}
- If-Else Statement js
var colour = " yellow";
if (colour == "red") {
console.log(" stop the car ");
}
else if (colour == "green") {
console.log(" go ");
}
else if (colour = "yellow") {
console.log(" get ready foe the car ");
}
else {
console.log("there is no colour ");
}
Switch Statement:
- Switch Statement ts
let day : string = "monday";
switch (day){
case "monday":
console.log("today monday");
break;
case "tuseday":
console.log("today tuseday");
break;
case "wednesday":
console.log("today wednesday");
break;
}
///today monday
- Switch Statement js
var day = "monday";
switch (day) {
case "monday":
console.log("today monday");
break;
case "tuseday":
console.log("today tuseday");
break;
case "wednesday":
console.log("today wednesday");
break;
}
///today mondayloop in typescript:
// for loop in ts
for (let i = 0; i < 5; i++) {
console.log( 'Iteration ' + i );
}
///
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Comments
Post a Comment