8 ms·
That's distinguishing the String class from primitive string. I don't think that would still work with another `extends String` the same shape as Hash. For exa
by brlewis 2y ago
That's distinguishing the String class from primitive string. I don't think that would still work with another `extends String` the same shape as Hash.
For example: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABOARgJwIZgCYFNsAiuAtnABQCUiA3gFCKIQA2GAzq4gIJgzEZM16DRDFYApDAHMQGNAC5EKOHCa4siALyJg-VrgDcQgL60hzNh04gocUihirBwkeKkz5i5avVadTPYYMJkKgkLAIiLhgkjBguADKcODYZBCyClY2dg64VHTOaLhQIGhIaWgAdKIS0rKIAPyIAEQAbmjKxE2ICk0ADtaI-VBNgYjBDBAIrCq4FUxwkmRRMXGJyWQALABMFBT6iAD0B4gAKgCevQkQaDC9UIy2vSyxrGZTM3MLS9GxCUk4ZDiAHcuDw+ExKLt9kdThcrjc7ohsHBcBwwHB7pNiE8MLFaCYgA 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 complain
- mason55 2y agoOr, a version that's more inline with the post you're replying to. Just 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/MYGwhgzhAEASkAtoFMAeAXZA7AJjAyugE4CWWA5tAN4C+AUKJDAKIC2YJIKG2e0hpCtXp0A9KOgBJHMjAgQATwA00AO7JoAeyyK1YLOmjpN0AA5NoCRMhjGjCEjABmAVyzB0JbQ20RDwTVZzImR4CCQAXmgACitwgC44RBUyUxd0RL9BcgBKRIAjTU0QWSxoCIA+ajpoaBD0FyIy4hdkAG46Gg6fLD9ocmxkIjBMNg4uKOjU9MziMlzEsc5yqqoauuQGpugsZFVoJZAprDT0HI6RcQPUMCCS6BcIMAGevsehyRP08ugAIghkMB6gAREZgX4dAK9QzIdjLKIDXbDUZwo7vIifU7nOhiCQAdQQRVMEBU6jMTGQOGg+hQqOpMDAlkQr0M7HQwAQNh+ASCYBCYQQ0Vh4xU6Mx6XOQA https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoF...
- jacobsimon 2y agoOops you’re right!