3 ms·
It doesn't take much "leveraging" to do this in a language with ADTs. E.g. Typescript type Book = { id: number; name: string; genre: Genr
by mssundaram 6y ago
It doesn't take much "leveraging" to do this in a language with ADTs. E.g. Typescript
type Book = {
id: number;
name: string;
genre: Genre;
};
type Genre =
| "Adventure"
| "Comic"
| "Crime"
| "Fiction"
| "Fantasy"
| "Historical"
| "Horror"
| "Magic"
| "Mystery"
| "Philosophical"
| "Political"
| "Romance"
| "Science"
| "Superhero"
| "Thriller"
| "Western";
- ed25519FUUU 6y agoThe benefit to having a type is mainly IDE experience and catching it at compile time. It's easiest to say `Genre.WESTERN` than using the string `western` and hoping you didn't accidentally type `westrn` and get a runtime error.
- mssundaram 6y agoconst someBook: Book = { id: 1, name: "Title", genre: "wstern" // Compile error: [tsserver 2322] [E] Type '"westrn"' is not assignable to type 'Genre'. }; That's not how string literals work in Typescript. If you mis-type the string you'll get a compile error. It won't make it to runtime.
- wffurr 6y agoCompile time checks on the strings are exactly what you get with that TypeScript definition above.
- christiansakai 6y agoAs a JavaScript developer I once abhorred TypeScript, until I realized TypeScript's type system is really powerful, it can do something like <Parameters<GetSomeFunc>> and <ReturnType<DoThisFunc>>. Mind. Blown.
- mssundaram 6y agoYeah, when I first came across TS, I didn't see the point, mostly because I didn't see how powerful Typescript's type system is - it gets more amazing by the day, too.
- mdtusz 6y agoWhile typescript typing is extremely powerful and expressive, I sometimes find that code written with it overuses some of the features in order to make types and interfaces align, rather than rethinking the design altogether. Especially with generics, things can get overly complex precisely because of the ability to extract return types, use partial types, omit fields, etc. My biggest typescript gripe is the fact that interface and type are _nearly_ interchangable, and many codebases just use interface wholemeal where it isn't really appropriate.
- christiansakai 6y agoI tried to refactor a big code base without these special helper types, it was a massive amount of duplication, to the point I just copy paste it or just aggregate it into one folder and making it leak everywhere on my layers. The type and interface is just because they are structural typing. It's attempting to stay faithful to JavaScript after all. Without that then the intuition breaks and not consistent.