You can still do this with classes in typescript:
class Hash extends String {}
https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoF...
class Hash extends String {}
https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoF...
For example: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABO...
class Animal {
isJaguar: boolean = false;
}
class Automobile {
isJaguar: boolean = false;
}
function engineSound(car: Automobile) {
return car.isJaguar ? "vroom" : "put put";
}
console.log(engineSound(42)); // TypeScript complains
console.log(engineSound(new Animal())); // TypeScript does not complainJust add an Email class that also extends String and you can see that you can pass an Email to the compareHash function without it complaining.
class Hash extends String {}
class Email extends String {}
// Ideally, we only want to pass hashes to this function
const compareHash = (hash: Hash, input: string): boolean => {
return true;
};
const generateEmail = (input: string): Email => {
return new Email(input);
}
// Example usage
const userInput = "secretData";
const email = generateEmail(userInput);
// Whoops, we passed an email as a hash and TS doesn't complain
const matches = compareHash(email, userInput);
https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoF...https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoF...
[0] https://flow.org/try/#1N4Igxg9gdgZglgcxALlAIwIZoKYBsD6uEEAzt...