giritharan
Tue May 07 2024
Typescript Learning
Variable definition: In Typescript we can specify the type string, number and boolean like
let myName: string = "Vijay";
let age: number = 20;
let isActive: boolean = false;
Moreover, if we don't specify the type typescript automatically detects the type by itself. But end of the defining the type was a good convention.
Function Definition: • For defining a function we can specify the function parameters type. Along with that we can able to set the default value. And also the return value.
function sum(a: number, b: number = 2): number {
return a + b;
}
• For Arrow function:
let sum = (a: number, b: number = 2): number => a + b;
Why don't use any
:
• Using any
in TypeScript bypasses type checking but undermines TypeScript's static typing advantages. It's better to specify types explicitly for safer and more maintainable code.
Array:
With the help of the array, we can store number, string and boolean values separately and mixed.
For String
let users: string[] = ["a", "b", "c", "d]
For Number
let count: number[] = [1, 2, 3, 4]
For boolean
let isActive: boolean[] = [true, false]
For Mixed array
let allDate: (string | number)[] = ["a", "b", "c", 1]
Here Array contains only integers and strings
Void And Never:
• void
is a type that represents the absence of returning value. It's often used as the return type of function that doesn't return any value.
function logError(msg: string): void {
console.log(msg);
}
• never
represents the type of values that never occur:. It's typically used as the return type of functions that never return (i.e., always throw an error).
function throwError(message: string): never {
throw new Error(message);
}
Object Type:
• Object Types
is used to pass the object as a parameter in the functions.
function fetchData(pt: { x: number; y: number }) {
return pt;
}
fetchData({ x: 3, y: 7 });
• If we want mentioned as an optional prop we can do that with the help of ?
operator
function fetchData(pt: { x: number; y?: number }) {
return pt;
}
fetchData({ x: 3 });
Union Types: • It means type can be formed in two or more types, which means values can be anything from the union value.
function sum(a: string | number) {
return a;
}
Here you can see value can be anything string or number
Type Aliases
• When can use both object type and union type but if we want use more than once we can use Type Aliases
or Interface
.
type User = {
name: string;
age: number;
}
function displayUser(prop: User) {
console.log(prop.name);
console.log(prop.age);
}
displayUser({name: 'John', age: 22})
• Moreover on the type, we can able to do extend the values.
type User = {
name: string;
age: number;
}
type Role = {
role: string
}
type UserDeatils = User & Role & {
address: string;
}
• From above you can see that the userDetails inherits the user and role props without adding extra value. So that helps to keep DRY over time. Interface: • Interface is also similar in concept to type_._ it's another way to name an object type.
interface User {
name: string;
age: number;
}
function displayUser(prop: User) {
console.log(prop.name);
console.log(prop.age);
}
displayUser({name: 'John', age: 22})
• It allows the extending feature.
interface User {
name: string;
age: number;
}
interface Role {
role: string
}
interface userDetails extends User, Role {
address: string;
}
• The Only difference is type not available for re-opening for adding new properties. Readonly and Optional: • with the help of that, we can mark the value as read-only or optional.
type User = {
readonly id: string;
name: string;
phone: number;
isActive: boolean;
email?: string;
};
• If we try to access id typescript will throw an exception
. Also, email is not present on obj it does not make exceptions.
Tuples:
• Tuples are a data structure that allows you to store a fixed-size, ordered collection of elements.
• Each element in a tuple may have a different data type. They are similar to arrays, but their size and types are fixed once they are defined.
let myTuple: [string, number, boolean];
myTuple = ['hello', 10, true];
• In typles we can modify elements of the tuple using array method with different types. It doesn't show any warning we always need to be aware of it.
Enums:
• Enums in TypeScript are usually used to represent a determined number of options for a given value.
• TypeScript provides both numeric and string-based enums
• Numeric enums:
▪︎ By default enum value starts from 0
until we explicitly mention something:
const enum UserType {
ADMIN,
USER,
GUEST,
}
• We can explicitly change the enum value
const enum UserType {
ADMIN = 10,
USER,
GUEST,
}
• so from now value goes like 11, 12 in upstream • String enums: ◦ String enums are similar to numbers, But here we can specify string instead of numeric
const enum UserType {
ADMIN = "admin",
USER = "user",
GUEST = "guest",
}
• Heterogeneous enums: ◦ We can mix up string and numeric on enum. But After string, if numeric get started we need to mention the numeric value for the first one.
const enum UserType {
ADMIN = "admin",
USER = 0,
GUEST,
}
• Remaining value can typescript will handles. #typescript #javascript