Typescript - Usage of Extend ,Enum And Read Only Keywords

Extend: In situations where you want to create a type by building on top of an existing one, you can use an ampersand (&) to do that.

Look at how we extend the Person type with additional props to emulate a database entry (PersonEntry).

type person = {
    name: string,
    age: Number
}

type personEntry = person & {
    id: string,
    createdAt: Date,
    updatedAt: Date
}


const data : personEntry = {
    id:"1ABC13",
    createdAt : new Date(),
    updatedAt : new Date(),
    name: 'xyz',
    age:31
}

Readonly<Type>: We can make objects immutable (properties can't be changed) by simply applying the Readonly utility type.

In this example, we create an object of type persondetail and can still change its props.

In the second example, we make it immutable.

type persondetail = {
    name: string,
    age: Number
}

const fisrtdata : persondetail = {
    name: 'xyz',
    age:31
}

//changing properties is still possible
fisrtdata.age = 32;

const seconddata : Readonly<persondetail> = {
    name: 'xyz',
    age:31
}

//changing properties leads to a type error
seconddata.age = 32;

Enums are a useful type if you have a list of discrete values (e.g. directions, weekdays, month names, ...).

Sometimes we want to get just the values as a new union string type.

With template literals, we can dynamically generate that.

enum Direction {
    North = "N",
    East="E",
    South="S",
    West="W"
}

const directionviaEnum: Direction[] = [
    Direction.North,
    Direction.East,
    Direction.South,
    Direction.West,
]


//Convert enum values into a union type
type directionType = `${Direction}`;
const directionviaType: directionType[] = [
    'N',
    'E',
    'S',
    'W',
]

Template Literals: You can use string template literals to generate dynamically new interesting union types of string literals.

Let's generate all possible word combinations using 2 predefined union types (Fruit and adjectives).

type Fruit = 'Apple' | 'Banana' | 'Mango'
type Adjective = 'Juicy' | 'Fruity' | 'Fresh'

type Label = `${Fruit} ${Adjective}`

Literal Types: You can use literal types to narrow down the allowed values even further.

When you combine it with the union type (pipe symbol) you can build interesting value checks.

Like in this example, the array will only accept these 4 values.

type Year = 2019 | 2020 | 2021 | 2022;

const Years : Year[] =[
    2018,
    2019,
    2020,
    2021,
    2022,
    2023,
    2024,
    2015,
    2026,
    2025
] 
Next Recommended Reading Get Set in TypeScript