Mapped type in typescript simply allow us create a new type by iterating over a list of properties.
Inother words, it allows you to take an existing type and transform each of its properties in some way to create a new type.
CONCEPT IN TYPESCRIPT
Readonly: It makes all the properties of an object type in typescript readonly. This means once a value is assigned to a property, it can not be changed.
type User = {
name: string;
age: number;
};
const user: Readonly<User> = {
name: "Mariam",
age: 30,
};
// user.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.
Generic Type: It allows you create reusable components that work with variety of types rather than a single one.
function identity<T>(arg: T): T {
return arg;
}
let stringIdentity = identity<string>("hello");
let numberIdentity = identity<number>(42);
Record: The record utility type constructs an object type whose property keys are keys and whose values are type.
type RecordType = Record<string, number>;
const myRecord: RecordType = {
apples: 10,
oranges: 20,
};
Pick: It allows you create a new type by picking a set of properties from an existing types.
type User = {
name: string;
age: number;
email: string;
};
type UserPreview = Pick<User, "name" | "email">;
const user: UserPreview = {
name: "Mariam",
email: "mariam@example.com",
// age: 30, // Error: Property 'age' does not exist on type 'UserPreview'.
};
Index Signature: I.S allow to define the type of values that can be assessed with an index. It's useful when the exact properties of an object type are not known in advance.
type StringArray = {
};
const myArray: StringArray = ["hello", "world"];
Optional: Optional properties are properties that may or may not be present in an object. You define them with "?".
type User = {
name: string;
age?: number; // age is optional
};
const user1: User = { name: "Mariam" };
const user2: User = { name: "Ade", age: 25 };
Intersection: Intersection types combine multiple types into one. It uses the & symbol.
type Person = {
name: string;
};
type Employee = {
employeeId: number;
};
type EmployeeDetails = Person & Employee;
const employee: EmployeeDetails = {
name: "Mariam",
employeeId: 1234,
};
Top comments (0)