Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Type Casting with TypeScript: A tutorial

Posted on Aug 30 • Originally published at deadsimplechat.com Type Casting is an important technique and technology, especially in TypeScript.TypeScript is a SuperSet of JavaScript that has strong typesafety and potential for catching errors during compiling rather then when the program is run.Here are some of the reasons why Type Casting is important in TypeScript.To understand the intended data type, it is important to TypeCast one type into another. This is true when working with nested data types or complex data typesThis way the developer can say what type they are expecting to the compiler. When working with complex data types and deeply nested data declaring the data types like this helps the compiler compile faster and increases productivity.If you want to ensure type safety and prevent run time errors in legacy JavaScript libraries that were not written in TypeScriptYou can do this by TypeCasting expected types and ensure safety of your code.When parsing JSON data or working with an external API, you might encounter unknown types.With Type Casting you can specify the expected type of value, thus making it easy to maintain and performant code.With technologies like conditional types and mapped types you can easily and efficiently do TypeCasting reducing redundancy and maintaining type safety thus making the code more expressiveWith TypeScript you can create custom Type Guard functions with the isType operator. Type casting helps assert if a given value is of a type that we are expecting it to be. Then If it is of the type we want it to be we can use the value in the next process or if the assert fails then we can think of what to do with the value.TypeScript might sometimes convert a value from one type to another, this usually happens in an assignment to a function call.The TypeScripts type checker automatically determines the inferred type of the given value and there is no manual intervention by the developerLet us consider an exampleExplicit Type casting is when the developer performs the type conversion intentionally, thus the developer explicitly provides the typeTypeScript offers 2 ways a developer might do thisTo cast a value to another type in TypeScript you need to place the type to cast in Angle Brackets followed by the value to castlet us look at an exampleThis method is an older way to type cast in TypeScript. Let us look at another modern may to Type Cast and that isthe as keyword was added in typescript as a way to Type Cast. This method is easy to use and more readable as well.The Older Angle Brackets method could also conflict with JSX and hence the as keyword is the prefferred way of Type Casting in TypeScriptLet us consider an exampleNo, Matter which method you use to typecast the TypeScript will ensure that the cast is valid and permitted.TypeScript will always look to maintain Type safety.Using Type Casting incorrectly can cause errors.What are Type Guards?Type Guards are functions. These functions narrow the scope of the given value to a perticular typeThis enables the typescript to differentiate between types.Creating custom type guards allows the developer to perform custom checks on the value and return a boolean type determining as to what the expected value of the type islet us look at an exampleWhat is functional Programming?Functional Programming means having functional principles such as immutability, higher order functions etcTo write maintainable and predictable code. Type Casting can also be done with functional programming methodology in typescriptLet us fo Type Casting with map functionWe are using conditional and mapped types to perform advanced Type Casting, We are also ensuring type safe while performing advanced type castingLet us learn some more about the advanced techniques and technologies in the next sectionThere are 2 techniques that we are going to learn today. 1. Reflection and runtime type metadata. 2. using consitional and mapped typesBoth these types are explained in detail below with examplesTypeScritpt be default provides type checking at compile time. If you need more dynamic type checking during run time you can use decorators and libraries such as reflect-metadata Reflection involves checking the data stucture of the type at runtimelet us consider an example using the reflect-matadatadefining types based on a perticular condition is known as Conditional types in TypeScriptThis article is brought to you by DeadSimpleChat, Chat API and SDK for your website and app.The condition types have a particular syntax and that isWhich means if T extends you then the type is X otherwise it is Y.You can iterate over existing types and modify their properties as needed to create new typesFor example: We can create different versions of the same type that is read-onlyUsing conditional and mapped types, we can do complex Type Casting with TypeScriptTypeScript empowers developers with tools such as reflection and runtime metadata, conditional and mapped types and ensures type safety throughout your. codeIn this example we will be using type casting to check the type of Object parse by the function JSON.parseJavaScript's built in function JSON.parse can parse a JSON string into a JavaScript ObjectHowever TypeScript does not know what is the type of object parsed by the JSON.parse functionWe will be using Type Casting to provide the correct type informationNext we will be creating a custom guard function to validate the structure of JSON that is parsed with JSON.parse functionNow, we have created a custom function that we can use to assert the type of JSON that was parsed by JSON.parse functionLet us now assert that the JSON parsed by the JSON.parse Object is of a particular type or not.In this above example we are using a custom guard function isIndividual to check that the parsed JSON is of the type IndividualThe Individual Object here is serving as an implicit type cast and maintains safty and code integrityIn this example we will be transforming JSON API responses with a utility function and using type manipulation techniques to achieve type safetyAs a sample api we will be using the JSON placeholder websites todos apihttps://jsonplaceholder.typicode.com/This endpoint returns the following data:We are going to create a function that would fetch the data from the todos endpointWe know that it is not guaranteed that the JSON responses we recieve from the endpoint are not always going to be in the structure or format that we require them to beWe can create a utility function that checks and narrows the type of response using a Type check functionWe are going to handle the JSON responses using the utility functionIn the above example we are using the fetched data from the JSON placeholder website and using a utility function to check the JSON response and assert the type of JSON using a functionDeadSimpleChat is an Chat API providerIn this article we learned about TypeCasting in TypeScriptWe learned about the imporatance of TypeCasting, and what are the basic principles of typecasting, real world application and other things that are required in TypeCasting with TypeScript like safety and implicit and explicit type castingWe covered modern technologies and demonstrated real life examples using JSON and API responsesI hope you liked the article and thank you for reading.Templates let you quickly answer FAQs or store snippets for re-use.I hope you liked the article. Thank you for reading Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Edwin - Aug 29 Durgesh kumar prajapati - Aug 30 Kingsley Ubah - Aug 29 yatendra2001 - Aug 29 Once suspended, alakkadshaw will not be able to comment or publish posts until their suspension is removed. Once unsuspended, alakkadshaw will be able to comment and publish posts again. Once unpublished, all posts by alakkadshaw will become hidden and only accessible to themselves. If alakkadshaw is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to alakkadshaw. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag alakkadshaw: alakkadshaw consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging alakkadshaw will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Type Casting with TypeScript: A tutorial

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×