avatarBytefer

Summarize

Very Useful Tricks for TypeScript as const

These 5 Tricks Make It Easy To Solve Some of the Problems You Encounter in Your Work.

Photo by Sam Dan Truong on Unsplash

Welcome to the Mastering TypeScript series. This series will introduce the core knowledge and techniques of TypeScript.

In TypeScript, as const is a type assertion that marks a variable as “constant”. Using as const tells the TypeScript compiler that all properties of an object are read-only and that their types are literal types, rather than more general types such as string or number. In this article, I will introduce 5 tricks for using as const type assertions in TypeScript.

1. Ensure object properties are immutable

In the code below, although you use the const keyword to define the DEFAULT_SERVER_CONFIG constant. But you can still modify the object’s properties.

const DEFAULT_SERVER_CONFIG = {
    host: "localhost",
    port: 8080
}

DEFAULT_SERVER_CONFIG.port = 9090
console.log(`Server Host: ${DEFAULT_SERVER_CONFIG.port}`)
// "Server Host: 9090"

And if you want the object’s properties to be read-only and not allowed to be modified, then you can use the as const type assertion.

const DEFAULT_SERVER_CONFIG = {
    host: "localhost",
    port: 8080
} as const

Later, when you try to modify the portproperty, the TypeScript compiler will prompt the following error message:

as const type assertion, in addition to supporting ordinary objects, also supports nested objects:

const DEFAULT_CONFIG = {
    server: {
        host: "localhost",
        port: 8080
    },
    database: {
        user: "root",
        password: "root"
    }
} as const

2. Ensure an array or tuple is immutable

Arrays are a common array structure at work. Using the as const type assertion, we can make the array read-only.

const RGB_COLORS = ["red", "green", "blue"] as const

After using the as const type assertion, the type of the RGB_COLORS constant is inferred as the readonly [“red”, “green”, “blue”] type. Later, when you add a new color to the RGB_COLORS array, the TypeScript compiler will prompt the following error message:

RGB_COLORS.push("white") // Error

In addition to arrays, you can also use as const type assertions on tuples:

const person = ['kakuqo', 30, true] as const;

person[0] = 'bytefer' // Error
// Cannot assign to '0' because it is a read-only property.(2540)

3. Alternatives to constant enums

In the following code, we define the Colors enumeration type using the enum keyword.

const enum Colors {
  Red = 'RED',
  Green = 'GREEN',
  Blue = 'BLUE',
}

let color: Colors = Colors.Red; // Ok
color = Colors.Green // Ok

In addition to using enumerated types, you can also achieve similar functionality using as const type assertions:

const Colors = {
  Red: 'RED',
  Green: 'GREEN',
  Blue: 'BLUE',
} as const;

type ColorKeys = keyof typeof Colors;
type ColorValues = typeof Colors[ColorKeys]

let color: ColorValues = 'RED'; // Ok
color = 'GREEN'; // Ok

4. Make type inference more accurate

In the following code, the type of the red variable is inferred to be of type string.

const RGB_COLORS = ["red", "green", "blue"];

let red = RGB_COLORS[0] // string

In some cases, you may want to obtain a more precise type, such as the corresponding literal type. In this case, you can use the as const type assertion:

const RGB_COLORS = ["red", "green", "blue"] as const;

let red = RGB_COLORS[0] // "red"

5. Narrow the type of a variable when assigning

In the following code, the type of a constant defined using the const keyword will be inferred to a more precise type.

let color1 = "Red" // let color1: string
const color2 = "Red" // const color2: "Red"

Using the as const type assertion, we can also make the type corresponding to the variable defined by the let keyword more precise:

let color3 = "Red" as const // let color3: "Red"

Of course, in actual work, if the constant is clearly defined, it is recommended to use the const keyword to define it directly.

TypeScript is awesome and worth learning, if you like to learn TypeScript, you can follow me on Medium or Twitter to read more about TS and JS!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

If you enjoyed this article, consider trying out the AI service I recommend. It provides the same performance and functions to ChatGPT Plus(GPT-4) but more cost-effective, at just $6/month (Special offer for $1/month). Click here to try ZAI.chat.

Programming
Web Development
JavaScript
Typescript
Front End Development
Recommended from ReadMedium