Typescript Notes
What is TypeScript?
TypeScript is a programming language built on top of JavaScript.
It adds types to JavaScript which helps catch errors early and makes code easier to understand.
Reference
() {} []
Primitive
a) Number
Used for integers and decimal numbers.
b) String
Used for text.
c) Boolean
Used for true or false values
d) Any
Can store any type of value.
Avoid using too much because it removes type safety.
unknown
unknown is a type-safe version of any.
It means:
value can be anything
but TypeScript will force you to check the type before using it
You cannot directly use methods or operations on it.
TypeScript gives error because it does not know if value is really a string.
e) Undefined
Variable declared but no value assigned.
f) Null
Represents empty value.
g)BigInt Example
Used for very large numbers.
h) Symbol Example
Used for unique identifiers.
Arrays
Arrays store multiple values of the same type.
Array of Numbers
Array of Strings
Another Array Syntax
Mixed Array using any
Tuples
Tuple is a special array where:
number of elements is fixed
types are fixed in order
Explanation:
First value must be string
Second value must be number
Enums
Enum (Enumeration) is used to store a group of related constants.
It makes code more readable and easier to manage.
Void
void means a function does not return any value.
Used mostly in functions.
This function only prints something.
It does not return anything.
Type Inference
Type Annotations
Interface and Type Alias
Interface is used to define the structure of an object.
It describes:
properties
data types
methods
Optional Properties
Readonly Property
Cannot be changed later.
interface with function
interface merges the same name objs
interface ko kam obj ko shape define garne
Extending Interface
extending an interface in TypeScript means
you take one interface and add more properties to it
simple idea: inherit + add extra
now Student has:
name
age
grade
Type Alias in TypeScript
What is Type Alias?
Type alias creates a custom type using type.
in TypeScript, a type alias is just a way to give a name to a type. simple.
now you can reuse it:
type ko kam chai type deifine garne datatypes use garera
a union in TypeScript means
👉 a value can be one of multiple types
simple idea: “this OR that”
intersection
C now has:
name
age
Classes and Objects
In TypeScript, classes and objects work almost same like Java or C#. TypeScript adds type
safety on top of JavaScript.
A class is a template to make objects.
Object
Object = collection of data (key + value)
No class needed
No constructor needed
Constructer