TypeScript Unlocked:  Readonly, Optional and Type Mixing

TypeScript Unlocked: Readonly, Optional and Type Mixing

·

3 min read

💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.

Readonly

Readonly feature enables us to make properties of the an object readonly. This means we cannot change the value once it has been set, it can only be read.

type User = {
    readonly id: number, // making id readonly
    name: string,
    age: number,
}

const user1: User = {
    id: 123212,
    name: "Palash Dhavle",
    age: 24
}

user1.id = 31 // this will raise an error

I am using the readonly keyword for the id to make it readonly. Now we restrict changes to id property therefore the last line where I try to modify the id will throw an error. In some scenarios using readonly can make our code prone to less bugs.

Optional

Optional is very self explanatory. Sometimes we might not want to make it compulsory to add each and every property while creating an new instance of an object. So we mark some properties as optional.

type User = {
    readonly id: number, // making id readonly
    name: string,
    age: number,
    address?: string // making address optional
}

const user1: User = {
    id: 123212,
    name: "Palash Dhavle",
    age: 24
}

const user2: User = {
    id: 123213,
    name: "Tony Stark",
    age: 24,
    address:"10880 Malibu Point, Malibu, California"
}

To make a property optional we just have to put a question mark before the colon(:). In this case both user1 and user2 is valid because we have marked the property as optional.

Type mixing

Sometimes we may need an object which is equivalent of combination of two three objects and each object may have more than 10+ keys. So in this situation instead of re-writing all the keys again and defining the type again we use something called type mixing.

type User = {
    readonly id: number, // making id readonly
    name: string,
    age: number,
    address?: string // making address optional
}

type BankInfo = {
    accNo: number,
    accHolderName: string
    branch: string
}

type education = {
    highestDegree: string
    marks: number
}

// Using type Mixing
type userInfo = User & BankInfo & education

let newUser: userInfo = {
    id: 1234321,
    name: "Palash Dhavle",
    age: 19,
    accNo: 3456787653232,
    accHolderName: "Palash",
    branch: "Mumbai",
    highestDegree: "Phd",
    marks: 500

}

This syntax is convenient when we face these kind of situation.

if you reached till here and you liked what you read don't forget LIKE to SHARE it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!

Â