What is TypeScript?
On a basic level, TypeScript allows you to set variables so that they can only be assignable to a specific data type.
|What is TypeScript and how does it work?|
Written by Microsoft engineers and architects David Nalidikumutadilla and Edward Z. Yang, there are numerous tutorials online for anyone wanting to learn how to use TypeScript.
- Arrow Functions
Read also: What Is Web 3.0 And Why Does It Matter?
In this article, we will go over what TypeScript is, why you might want to use it, and how to get started.
Second, even if you aren’t a developer, you probably need to handle some complex interactions between content (e.g google maps, modals, widgets) and your web page. You can’t just assume that everyone has browser extensions enabled since those things require permissions from the user.
Third, there are lots of websites that work well until you look closer at them. Then you find out that they are loading resources like Flash or interacting with Web APIs that are no longer supported. For example, when you click on a link and then start typing into a search box, this makes the request via Ajax instead of through HTTP GET.
Because these sites were built before the rise of cross-platform development platforms such as Electron or NwJS, there was no real incentive to optimize performance. When developing apps for mobile devices then optimizing for speed is easier than testing different browsers and supporting features such as device automation or local storage
Why you SHOULD use it
Type Script grants us some convenient benefits such as:
//Static Typing (C++/C#/Java) int number = 5; // This is fine number = 'abc'; // this will error
- TypeScript compilation allows us to find errors in our typescript at compile time as opposed to when we run our application or unit tests.
- Shorthand notations
- Most code editors nowadays have support for typescript which enables us even more benefits such as:
- Code Completion
Why you SHOULDN'T use it
When Should you use it?
Simply put, TypeScript's benefits are more apparent when working on medium to large projects and/or with a team of developers to ensure they and you don't have any unexpected problems when running your program.
Welcome to the wonderful world of Typescript!
You’ll learn how to enable type checking when editing your code files, and what tools are available for doing it. You’ll also learn how to use several key features that help make development faster and easier.
Note that this tutorial is written for version 2 of typescript. If you’re using earlier versions, some things may work differently, can be deprecated, or missing.
Also note that while writing this article, we used typescript itself to create a simple project to demonstrate its capabilities. You can find the source code for this project here: https://github.com/jslinterceptors/ts-interceptor-demo
We will discuss why you might want to try to at end of this article.
But first, let’s see how to get started with typescript coding to develop software applications.
Where to start with TypeScript
That’s right, TypeScript is another option for writing flexible script-based applications. And what’s interesting about TypeScript is that you don’t have to use it. You can write scripts in any JS framework or software library you like.
Getting Started with TypeScript
In your code editor's terminal, you'll use your node package manager (or npm) to install typescript globally by running the command:
npm i -g typescript
Once the installation is complete you can verify the installation by running:
tsc -v and you should receive a response with the version number.
After verifying that you have the type script installed, you can start writing your first TypeScript program by creating a .ts file.
let age: number = 28;
If you were to try to reassign this value to something other than another number you will get an error.
Now that we have a single line of TypeScript code, we can run the command: 'tsc ' to run our compiler and transpile our .ts file into a .js file.
You should see the new .js file now and inside of it would look something like this:
var age = 28
Configuring the TYPESCRIPT Compiler
To do this, run 'tsc --init' in your terminal. This will create a tsconfig.json file which you can modify to fit your needs.
|configuring TYPESCRIPT Compiler example|
To use a configuration you will just have to uncomment the line you wish to configure. There are a lot of configurations in this file that you don't necessarily need to understand but the more common ones are:
- target: You can set this to any ES version (ES2016/ES2017/ES2018...). ES2016 is a very common and most used version so that will likely work best for you in most situations.
- rootDir: The configuration that specifies the directory that contains our src files. By default, it is set to "./" which represents the current folder.
- outDir: This configuration specifies the directory where our transpiled.js files will be sent.
- removeComments: If you add this configuration and keep it set to true, any comments you typed in your TypeScript code will not be transpiled in your .js files.
- noEmitOnError: This will stop the compiler if there are any errors in our TypeScript code.
After you finish setting up your configuration, you can now run 'tsc' instead of 'tsc ' to transpile ALL .ts files in your application.
But there are benefits to using TypeScript, especially since most front-end devs now know how to code. Learn more about the advantages here >
What is a type?
When you write code, you use types to enforce good coding practices. With types, there’s more confidence that your program will correctly run.
Types can help make sure your codebase isn’t filled with bugs or flaws. They can also help ensure that new people added to the project aren’t overburdened with learning about the inner workings of the app.
For example, if you are writing some custom functions for an application, it would be helpful to add type definitions into the project so programmers don’t have to worry as they use these functions.
There are many different types you can define in Typescript, but let’s look at one in detail. To do this, we’ll need to create a new file inside our project folder. We’re going to name this file my-type.ts.
Here, you can see what type definition looks like.
One of the most common features in any language is type conversion. Even if you’re writing PHP, which doesn’t have type conversion, you can still use it by enabling it in your scripts.
PHP allows you to perform type casting easily. When used effectively, it prevents vulnerabilities such as injection or log stuffing.
In PHP, there are two ways to do typecasting. The first one is using the ‘ (double arrow) symbol followed by the variable name.
For example, assign numeric values to variables using that symbol. Then, at the end of the assignment statement include the extension syntax where variable = variable → cast, etc. This way we can limit the scope of our typing and make sure that our data fits into the appropriate types.
The second method requires the use of single quotes around variable names. Thus they can be converted directly from string datatypes. However, this is less safe than the previous method. It cannot protect us from issues like XSSI though.
Type casting also reduces compatibility problems when working with languages such as JSX and React since they both support similar type conversions.
Let’s take this example from above. We have a Person class with first name, last name, and age property. With only two properties inside the person class, we already have three types that need to be inferred by the compiler.
The infer option –strict will make the process take longer but the result will be better. In our case, it will try to determine the type for us using some rules it has built-in.
In the case of assigning someone to a variable, like a john below. The compiler will know that data should come back from the assignment knowing that john won’t be null or undefined.
This helps prevent common mistakes such as handing people code that expects certain inputs which might not exist (like passwords without any characters) or outputs which don’t match up (such as a login form that requires user input).
Building types with type declaration
A typed language is a programming language that has explicit typing. The compiler checks your code to make sure it follows certain constraints. This can prevent bugs and help avoid mistakes. Using typed languages also helps developers write better software because they use more structured tools.
The easiest way to have some type checking in your programs is to use the built-in ‘typeof’ check. It will quickly become obsolete if you use another method instead. For example, typeof myVar === "number" is the same thing as doing Number(myVar)!== myVar, but easier to read.
But what if you want to use something else other than typeof? There are two main libraries for this: typescript.org and flowtype.com
Writing code from an interface is one of the core concepts in programming today. Well, it’s called encapsulation, but everybody calls it writing code from an interface.
There are two ways to write code that uses an interface: literal implementation or indirect abstraction.
A literal implementation means putting actual data into variables and using concrete types. The problem with this approach is that it can be very difficult to understand what’s going on under the hood.
Indirect abstractions solve this issue by creating a layer between your application and the internal mechanics of how you work. Your job as a programmer then becomes focusing on what you want to do rather than how you want to do it.
This is why indirect abstraction via interfaces is essential. By inserting a middle step, interfaces enable other people (or software) to do some things more easily.
For example, imagine you have a shopping app and you need to calculate shipping costs. You could create a separate function for calculating them and call that from within your addToCart() function, but if you used the API instead, you would just get the cost back out as part of the returned object.
Another benefit of using an interface is loose coupling. With tight coupling, all elements of your system will know about each other and any change will likely affect multiple systems.
By implementing components through their interfaces, they become loosely coupled, making evolution and maintenance easier.
Read also: What is Kotlin and why should you care?
There you have it, you should now know what is TypeScript and be set up to start typing in TypeScript! Of course, there are many more nuances to this Typescript programming language but I hope this was a good read to get you to start learning! Stay tuned for more information!
Post a Comment