4 ms·
The demo they posted demonstrates how to do it. But I don’t think it’s a generally good solution to the problem, it feels like it solves this specific case wher
by jacobsimon 2y ago
The demo they posted demonstrates how to do it. But I don’t think it’s a generally good solution to the problem, it feels like it solves this specific case where the type is a string hash. I think the evolution of this for other types and objects is more like what the OP article suggests.
I wonder if a more natural solution would be to extend the String class and use that to wrap/guard things:
class Hash extends String {}
compareHash(hash: Hash, input: string)
Here's an example: https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoFMAeAXZA7AJjAyugE4CWWA5tAN4C+AUHcAPZYTrTnbJFibwRIAvNAAUZAA4BXdAC5obUhQCUc-kIB81OtGhFk6SUSzQsyAO5xEYrFPRKA3NAD0T6ADEmRaDmQBbFgq8JCwANNBg4uLYOGSUAEQIiMg4APpx0OhM0BLSdDT2DC7QAJI+YCAgAJ5hZsjQLFXQZmBY7JnQ4pAwiQLIMO3oCCQwAGaSWMDowViMAezMvp16atDCIj0IqohhObLyxLEq0ABGTEwgyC2rmlTauvqGxsSSyAX5ha4AoqhgixfQkggYE4s1Y7EB3GKNmkq2gcQgyGAenQABFeGA4gVmGDoBtYZxTDw+FYIUQobYHB9oAB1EiDJgw448XDJDKVKIQMKDbjIADkMCwWTIMWAQRYGUSbQQdWRj1ZCli2RgYFxiAAdHQiijkAA3ZAgJhRIgwXxgSooIhEFjIBkQRrES7sOnhZX3ciScBeBUUE6IsAQiU8-kmIW+XzJEi8OrYzAYcLodBgYDSnAZIXoMIXMAxH3tXzDCFhZBq8ga7EQc7Fg3kdbqzIAVUi3AAwpBkCIlJTNa4AHJMKbAOrcjpgHjhzDG8J6bLGMjMS2I9ieHxEUFsaCm9DJvqwhZLZBqESk8nSMIbBxAA https://www.typescriptlang.org/play/?#code/MYGwhgzhAEASkAtoF...
- mason55 2y agoAs mentioned elsewhere, what this is actually doing is showing that string and String are not structurally equivalent in TS. If you add another class Email that extends String, you can pass it as a Hash without any problems. And you can get rid of the Hash stuff altogether and do something like compareHash(userInput, new String(userInput)); and that fails just as well as the Hash example. Using extends like this doesn't actually fix the problem for real.