Since its creation in 1995, to its takeover of the internet in 2005 we know that JavaScript has been the little scripting language that could. In its origin JavaScript was meant to be a easy and flexible language that would be ideal for small apps, nowadays we use it to build out dynamic web apps. However JavaScript still has its flaws such as not telling the programmer when a change will break something someplace else. To correct this in 2012 Microsoft released a new language that helps solve some of JavaScript’s problems, enter TypeScript.
TypeScript is a language that adds a type system to JavaScript, this helps refactor code, and spot bugs. An example of a change brought on by TypeScript is arrow functions TypeScript had the arrow functions, and classes before JavaScript, and now in JavaScript arrow functions are the way most functions are written.
When writing code using TypeScript we use files that end with a .ts we then run our file through a transpiler. A transpiler is a is a tool that reads source code and creates the equivalent code in another language, as long as it has a similar level of abstraction. If the code can be converted then the transpiler will give you a JavaScript version of the file so that file will be ending in .js now.
Now if you’re like me and you use VS code you can use the following command to install your TypeScript compiler :
npm install -g typescript
One note to keep in mind is that VS code could have a different version of TypeScript than the one you installed so check the bottom right status bar for version number.
One step to remember when creating a new TypeScript project is to create tsconfig.json file that will define things like compiler options and files to be included, basically the rules you want from the TS compiler, and it also allows to use tsc without arguments in terminal. To do this you will open a folder where you want to store your source and then add the file inside of it. Target is what version of EcmaScript standards you’ll be using for JavaScript. In this case its ‘es5’. Module means commonjs (https://nodejs.org/docs/latest/api/modules.html) this is the syntax to import and export modules.
Sample of tsconfig.json file{
"compilerOptions": {
"target": "es5", //
"module": "commonjs",
}
}
Once you are done with a file and want to convert it into a JS file you use the command tsc.
tsc NameOfFileToConvertToJs.ts//this will result in NameOfFileToConvertToJs.js
Now that we know how to setup TypeScript let’s talk about the language itself. In TypeScript we cannot reassign a variable to a different value type. TypeScript recognizes all of the primitive values of JS but if you try to do the following
let name = 'The Supah Jatt'name = 50results in the message (50 is not assignable to a string)name = '50' // this would be ok
However if we create a variable without a value, then TS will give the variable a type of any, variables with type any can be reassigned later without returning a error. Therefore the following is perfectly fine.
let number;number = 100
number = 'hundred'
Now what if you wanted to leave a variable undeclared but also didn’t want it to be assigned to any datatype, well fear not TS has type annotations which allow for just that. To use we set a colon after the name of the variable and then the type we want to allow. Example:
let onlyStrings : stringonlyStrings = 'Hello' // this is validonlyStrings = 65 // this returns an error
So TypeScript doesn’t like having ambiguity when it comes to declaring types, but it converts to JS in which functions play major role, and in these functions we pass in data types as arguments so how do we handle functions in TS? Here’s an example of function that returns info based on the type of data, which seems like nightmare for TS.
function typeOfInput(type) {
if (typeof text !== 'string') {
return('not a string!');
} else {
return true }
}
typeOfInput(0)
An easy way to get around this is use type annotations inside the parameters, therefore ensuring the type of data you want is entered, if not TS will throw an error. And in the case of multiple parameters we have to use type annotations for each parameter to avoid error.
function typeOfInput(name: string) {
return(`Hello, ${name}!`);
}
typeOfInput('jaskomal')
Also this with this format TS will require not only that we pass in the correct argument type, but also pass in an argument so we can’t leave that part blank. If we were to leave the argument blank then we will get error because blank will return a falsey value and falsey does not equal a string. To let TS know that the parameter is optional we have to include a ? after the parameter.
function typeOfInput(name?: string) {
return(`Hello, ${name || 'person'}`);
}
typeOfInput() // will return hello person
And if we wanted to set a default value to parameter, then the datatype that is the default value is what has to be passed in as the argument. We can leave the argument undefined since we have default value, and TS will not give us a type error. This is a better way to write the example above, by removing the need for the ? since we the default value tells us the parameters are optional.
function typeOfInput(name= 'person') {
return(`Hello, ${name}!`);
}
typeOfInput() // will return hello person
The last thing I want to go over about TypeScript functions is the explicit return type. After the closing parenthesis using the same syntax in the examples above we can add a explicit type annotation. So by putting a colon and then the type TypeScript will check if the value the function is returning is correct else it will throw an error.
function isString(name?: string): string {
if (name) {
return `Hello, ${name}!`;
}
return undefined;
undefined is not a string so it will give an error
};
This is just scratching the surface of all that TypeScript can do for us, its a tool to help fix bugs in JavaScript but it can do so much more. Really it makes life easier is worth learning so if you are someone who has just learned JavaScript and are thinking of where to go next, TypeScript would be a really smooth transition. Maybe even dare to say an easy one?