In advanced TypeScript scenarios, the use of ‘symbol‘ and ‘bigint‘ can be beneficial for various cases. These two data types were introduced to handle specific problem domains that were not well-covered by existing data types.
‘symbol‘ is a unique and immutable data type introduced to enable unique keys in objects, especially for avoiding name clashes among properties in complex code. Whenever you create a new symbol, it’s guaranteed to be unique, and it can never be changed.
‘bigint‘ is the newest numeric data type in TypeScript designed to provide support for arbitrarily large integers natively. Previously, integer values were represented using the ‘number‘ type, which could only handle integer values up to ‘2**53 - 1‘ (i.e., ‘Number.MAX_SAFE_INTEGER‘).
Let’s go through examples that show the advanced usage of ‘symbol‘ and ‘bigint‘ in TypeScript.
### Advanced Usage of ‘symbol‘
1. Defining unique property keys in objects or classes:
const firstName = Symbol("firstName");
const lastName = Symbol("lastName");
class Person {
[firstName]: string;
[lastName]: string;
constructor(first: string, last: string) {
this[firstName] = first;
this[lastName] = last;
}
getFullName(): string {
return this[firstName] + " " + this[lastName];
}
}
const p = new Person("John", "Doe");
console.log(p.getFullName()); // "John Doe"
2. Defining constants with non-overlapping values (similar to enumerated types):
const Red = Symbol("Red");
const Green = Symbol("Green");
const Blue = Symbol("Blue");
type Color = typeof Red | typeof Green | typeof Blue;
function getColorName(color: Color): string {
switch (color) {
case Red:
return "Red";
case Green:
return "Green";
case Blue:
return "Blue";
}
}
console.log(getColorName(Green)); // "Green"
### Advanced Usage of ‘bigint‘
1. Performing arithmetic on large integers:
const largeNumber: bigint = 1234567890123456789012345678901234567890n;
const anotherLargeNumber: bigint = 9876543210987654321098765432109876543210n;
const sum: bigint = largeNumber + anotherLargeNumber;
const product: bigint = largeNumber * anotherLargeNumber;
console.log(`Sum: ${sum}`);
console.log(`Product: ${product}`);
2. Handling large file sizes or other large quantities:
type FileSizeBytes = bigint;
class File {
name: string;
size: FileSizeBytes;
constructor(name: string, size: FileSizeBytes) {
this.name = name;
this.size = size;
}
getSizeInGigabytes(): string {
const bytesInGigabyte: bigint = 1_024n * 1_024n * 1_024n;
const gigabytes: bigint = this.size / bytesInGigabyte;
return `${gigabytes} GB`;
}
}
const largeFile = new File("example.txt", 50n * 1_024n * 1_024n * 1_024n);
console.log(largeFile.getSizeInGigabytes()); // "50 GB"
These examples should give you a good idea of some advanced scenarios where ‘symbol‘ and ‘bigint‘ can help you create more robust and reliable TypeScript code.