DEV Community

Discussion on: “Communicating your needs” / TypeScript’s value from a Buddhist perspective (part 1)

Collapse
 
zechdc profile image
zechdc

In your example, you mention that with typescript "this will never happen"

    // if(!newUserToSave.lastName){ // This if statement is unnecessary because you asked for what you need
    //     // this will never happen
    // }

Seems like Typescript helps reduce the chances of this happening, but it is actually a different check.

Typescript will tell the developer that lastName is required, but lastName could be an empty string at runtime. If it's important that lastName is not empty, you will still need the !newUserToSave.lastName check in your code.

I've been looking at adopting Typescript, but this is one issue I have with Typescript right now. The data I'm dealing with is legacy data and has lots of inconsistencies. The only way to catch stuff like this with the data I have is at runtime. It does seem valuable to know up front that lastName is a require property, but because it doesn't do runtime checking you can still get some invalid states.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Short version: just use io-ts or tsoa to help check for this at runtime.

Long version: You make a very good point however there are no programming languages that check the length or existence of a string at compile time. So in Java, modern C#, Kotlin, etc a string can still be empty. However, TypeScript and Kotlin can at least check for null and undefined unlike Java and older C#.

Think of this like an array of characters instead of a word. In fact, that’s how C++ represents strings (from what I can remember).

So since the length of an array is always a variable size the language can’t determine if the string is empty at compile time. But if you use a runtime validation library at your io layer or your API layer then you can clean the data before it gets too far into the code.

Collapse
 
zechdc profile image
zechdc

Thanks! That's a good point that no other language handles this case either. I'll look into io-ts and tsoa.