Generate Secure Random Token in TypeScript
In TypeScript, the way to generate a token is similar to JavaScript, because TypeScript will eventually be compiled into JavaScript code. Here is an example of a token generation function written in TypeScript:
First, make sure that your project has a TypeScript compilation environment set up. Then, you can create a .ts file and write the following code:
/\*\*
- Generates a secure token using the browser's crypto API.
- @param length - The desired length of the token.
- @param options - Optional configuration options.
- @param options.uppercase - Include uppercase letters. Default is true.
- @param options.lowercase - Include lowercase letters. Default is true.
- @param options.numbers - Include numbers. Default is true.
- @returns A secure token.
\*/
export function generateToken(length: number, options?: {
uppercase?: boolean;
lowercase?: boolean;
numbers?: boolean;
}): string {
const {
uppercase = true,
lowercase = true,
numbers = true,
} = options || {};
let charset = '';
if (uppercase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (lowercase) charset += 'abcdefghijklmnopqrstuvwxyz';
if (numbers) charset += '0123456789';
if (charset.length === 0) {
throw new Error('At least one character set must be selected.');
}
const buffer = new Uint8Array(length);
window.crypto.getRandomValues(buffer);
let token = '';
for (let i = 0; i < length; i++) {
token += charset[buffer[i] % charset.length];
}
return token;
}
In this TypeScript function, generateToken accepts two parameters: length (the length of the token) and an options object containing three optional boolean properties, which respectively indicate whether to include uppercase letters, lowercase letters, and numbers. Inside the function, a character set charset is constructed, and then Math.random is used to generate random indices. For each character of the token, a random index is generated and used to select a character from charset.
Please note that this example uses Math.random to generate random numbers, which is feasible in browsers, but for security-sensitive applications, you may need to use a more secure random number generation method, such as the crypto API.
In the example usage, we call the generateToken function and print the generated token. You can adjust the parameters of the generateToken function to generate tokens of different lengths and character sets as needed.