TypeScript Types Erased at Runtime, Use JavaScript Checks

So you're trying to verify types in TypeScript - it's a thing. But here's the deal, JavaScript doesn't really care about types at runtime. TypeScript types are basically erased after compilation, leaving you with just JavaScript values. You can do runtime checks, though - like checking if something's a string with `typeof x === "string"`, or if it's a Date object with `x instanceof Date`. Or, you know, checking if an object has a certain property with `"swim" in animal`. And then there's the `animal.kind === "fish"` check - that's a good one too. TypeScript uses these checks to narrow down union types, which is pretty cool. For example, you can use `typeof` narrowing in a function like `padLeft` - it takes a padding value that can be either a number or a string, and an input string. Or, you can use `instanceof` narrowing in a function like `logValue` - it takes a value that can be either a Date object or a string. And then there's the `"in"` narrowing - that's useful when you have a type like `Fish` that has a `swim` method. You can also reuse a check across multiple places using type predicates - like the `isFish` function that checks if an animal is a fish. It's like, you can use it to filter an array of animals and get only the fish. If you can change the data shape, using a `kind` property is a good idea - like, you can have a `Fish` type with a `kind` property that's set to `"fish"`. It's just easier that way. So, to sum it up: use JavaScript checks to narrow types, and type predicates to reuse the narrowing - that's the way to do it. Check out this article for more info: https://lnkd.in/gFKxe3ZE #TypeScript #TypeVerification #JavaScript

To view or add a comment, sign in

Explore content categories