create a password with a custom length in typescript

You can create a password with a custom length in TypeScript by generating a random string of characters. Here's an example function that generates a password of length n:

index.ts
function generatePassword(n: number): string {
  const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const numbers = "0123456789";
  const symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
  const allChars = letters + numbers + symbols;
  
  let password = "";
  for (let i = 0; i < n; i++) {
    const randomIndex = Math.floor(Math.random() * allChars.length);
    password += allChars[randomIndex];
  }
  return password;
}
438 chars
14 lines

This function creates a string that contains all the characters that can be used in the password. It then loops n times, generating a random index into the string and adding the character at that index to the password. Finally, it returns the password string.

To generate a password of length 10, you would call the function like this:

index.ts
const password = generatePassword(10);
console.log(password); // example output: "3fAs$2gTqX"
94 chars
3 lines

gistlibby LogSnag