avatarBytefer

Summary

The provided web content introduces five TypeScript as const tricks that help developers ensure immutability of objects and arrays, provide an alternative to constant enums, improve type inference accuracy, and narrow variable types for more precise type handling.

Abstract

The article delves into the utility of the as const type assertion in TypeScript, emphasizing its role in enhancing code safety and type precision. It explains how as const can be applied to objects to make their properties immutable, even when nested, and how it can render arrays and tuples read-only, preventing accidental modifications. The author also presents as const as a viable alternative to constant enums, allowing for similar functionality with a different approach. Additionally, the article illustrates how as const can lead to more accurate type inference, which is particularly useful when working with literal types. Lastly, it touches on the use of as const to narrow the type of variables, ensuring that they are assigned the most specific type possible. The article encourages TypeScript enthusiasts to follow the author on Medium and Twitter for more insights into TypeScript and JavaScript.

Opinions

  • The author suggests that using as const is beneficial for making objects and arrays immutable, which is a desirable feature in many programming scenarios.
  • The article implies that as const can serve as a practical substitute for constant enums, offering developers flexibility in how they define and use constant-like structures.
  • There is an emphasis on the importance of precise type inference and how as const can help achieve this, leading to more robust and error-resistant code.
  • The author's perspective is that TypeScript is an "awesome" language worth learning, and they encourage readers to engage with their content for further learning opportunities.
  • The inclusion of links to the author's Medium and Twitter profiles, as well as to the "Mastering TypeScript Series," suggests that the author values community engagement and continuous learning within the TypeScript and JavaScript developer community.

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:

Programming
Web Development
JavaScript
Typescript
Front End Development
Recommended from ReadMedium