unique Keyword in TypeScript

Do you want to know about the Typescript unique keyword? In this Typescript tutorial, I will explain how to use the unique keyword in Typescript.

To utilize the unique keyword in TypeScript, you apply it to symbol types to ensure their uniqueness. For example, type UserID = unique symbol; creates a unique identifier type, where each instance is distinct, preventing value duplication. This feature is especially useful for creating unique identifiers and ensuring unique property keys in objects, enhancing type safety and reliability in your TypeScript code.

What is the unique Keyword in Typescript?

TypeScript introduced the unique keyword as part of its type system. This keyword, when applied to a type, signifies that each instance of that type is distinct. This uniqueness is crucial in scenarios where values must not be duplicated, such as identifiers or keys in databases.

How Does unique Work in Typescript?

The unique keyword in Typescript works by creating a unique type signature for the values it annotates. This means that even if two values are structurally identical, they are considered different if marked with unique.

Typescript unique keyword examples

Now, let us see how to use the unique keyword in Typescript with a few examples.

Example 1: Unique Identifiers

One common use of the Typescript unique keyword is in the creation of unique identifiers. Let’s consider an example where we define a type for a user ID:

Here is the complete code:

type UserID = unique symbol;
let user1: UserID = Symbol("user1");
let user2: UserID = Symbol("user2");

// This will result in a TypeScript error
user1 = user2; // Error: Type 'UserID' is not assignable to type 'UserID'.

In this example, UserID is a unique symbol. Even though user1 and user2 are both of type UserID, they cannot be considered equal or interchangeable.

Example 2: Ensuring Unique Property Keys

Let us see another example of how to use the unique keyword in Typescript. Another application is ensuring property keys are unique in an object. Consider this scenario:

type PropertyKey = unique symbol;

const property1: PropertyKey = Symbol("property1");
const property2: PropertyKey = Symbol("property2");

let object = {
  [property1]: "Value 1",
  [property2]: "Value 2"
};

// Accessing values
console.log(object[property1]); // Outputs: "Value 1"

Here, property1 and property2 are unique symbols. They serve as keys in the object, guaranteeing no key collisions.

Conclusion

The unique keyword in TypeScript is a robust feature for ensuring type uniqueness. It plays a vital role in scenarios like unique identifiers and unique property keys. In this Typescript tutorial, I have explained how to use the unique keyword in Typescript.

You may also like:

>