The important thing here was the encoding of Shape.Ĭommunicating the right information to TypeScript - that Circle and Square were really two separate types with specific kind fields - was crucial.ĭoing that lets us write type-safe TypeScript code that looks no different than the JavaScript we would’ve written otherwise.įrom there, the type system was able to do the “right” thing and figure out the types in each branch of our switch statement.Īs an aside, try playing around with the above example and remove some of the return keywords. In many editors we can observe these types as they change, and we’ll even do so in our examples. It looks at these special checks (called type guards) and assignments, and the process of refining types to more specific types than declared is called narrowing. TypeScript follows possible paths of execution that our programs can take to analyze the most specific possible type of a value at a given position. Within our if check, TypeScript sees typeof padding = "number" and understands that as a special form of code called a type guard. Much like how TypeScript analyzes runtime values using static types, it overlays type analysis on JavaScript’s runtime control flow constructs like if/else, conditional ternaries, loops, truthiness checks, etc., which can all affect those types. While it might not look like much, there’s actually a lot going under the covers here. ![]() The idea is that TypeScript’s type system aims to make it as easy as possible to write typical JavaScript code without bending over backwards to get type safety. If this mostly looks like uninteresting JavaScript code, that’s sort of the point.Īpart from the annotations we put in place, this TypeScript code looks like JavaScript.
0 Comments
Leave a Reply. |