3 ms·
Narrowing involves actual types. I was referring to the compiler not checking mere value validation. I was referencing the kind of validation where someone che
by knome 3y ago
Narrowing involves actual types. I was referring to the compiler not checking mere value validation.
I was referencing the kind of validation where someone checks a bunch of attributes of a string, usually, or perhaps the range of an integer, but never actually does anything excepting in fail cases and then passes it on to other functions that then just expect those invariants to hold. I doubt typescript is remembering that my string doesn't have dashes in it or that it adheres to some regex, for example.
Type narrowing is fantastic for making things like nil punning work inside a complex type system.
I really like typescript's types. From where they started, they did an absolutely incredible job creating a robust and powerful type system that could manage almost any existing javascript code pattern.
Just really amazing work by the authors.
- riwsky 3y agoit will remember it if you ask it to, like in this example from https://www.typescriptlang.org/play#example/nominal-typing https://www.typescriptlang.org/play#example/nominal-typing : type ValidatedInputString = string & { __brand: "User Input Post Validation" }; const validateUserInput = (input: string) => { const simpleValidatedInput = input.replace(/\</g, "≤"); return simpleValidatedInput as ValidatedInputString; }; at runtime, simpleValidatedInput is still a string—it has not been parsed into a more specific type. The code just asserts (falsely) that it's a ValidatedInputString, and defines the latter in a way that prevents passing string-strings as ValidatedInputStrings.
- knome 3y agoI do appreciate your expounding on this, but I assure you I do get it. Using types to track these things is the appropriate solution. In most languages you would either create a wrapping object you can get the original back from or perhaps extend the basic type. Here we can just use `as` to cast the value into an intersection with the number, which I assume allows it to continue being used as a number but will catch failures on functions that needs a ValidatedInputString, in much the same way the an inherited subtype might. Probably better. I get it and you are right, this is the right thing to do. My original comment was that for those that do not do this appropriate type level work to track that we have validated a value, then it becomes an assumed aspect of the branch. This was very, very common in older code I've seen. I think I can safely assume that it still happens today, though if I am wrong I'll be glad that parsing the values into new types has made enough headway that it is seen as simply the default. Because it is certainly the RightThingToDo.
- riwsky 3y agoOh, yeah, it happens all the time even in TS code. We’re on the same page.