TypeScript-erific

Paul Ly
7 min readDec 24, 2018

Exploring some of the foundations and basics of TypeScript with JavaScript

Image result for typescript
https://cdn-images-1.medium.com/max/2000/1*D8Wwwce8wS3auLAiM3BQKA.jpeg

For those unfamiliar with TypeScript, it is a static-typed language for JavaScript. You can define and declare what your variables and functions will expect and return in terms of types.

var foo:string;
foo = 'happy holidays!';
foo = 123;
// Error

This is great for checking your inputs and outputs but also reassuring as you can always expect certain variables and functions to only handle the stated types. Not everyone deals with surprises as well as others! Just refer to Ellen DeGeneres’ videos on YouTube!

You could say this kinda ruins the dynamic-ness of JavaScript — but fortunately for you, even if you implement TypeScript, you aren’t required to define and declare the types for your variables and functions. AKA: TypeScript allows you to customize how structured and dependent you want your application to be.

This allows those converting to TypeScript to incrementally and gradually convert at their own pace. It allows developers to set their own sense of security and assurance. It, for the most part, seems to keep everyone happy!

function printMsg(message: string) {
console.log(message);
};
printMsg("Merry Christmas!!");printMsg(["Rudolph", "Reindeer", "Red-Nose"]);
// Error

You can define the argument types for functions with a colon followed by the type. But what if you have multiple arguments?

function calcProduct(num1: number, num2: number) {
return num1 * num2;
};
calcProduct(6,9);
// 54

But what if you have optional arguments?

function printMessages(msg1: string, msg2?: string) {
console.log(msg1);

if(msg2) {
console.log(msg2);
}
};
// add a question mark after it to declare an argument as optional or not and account for it in the function itself

As for as the function and its return type, you can define it as follows:

function doubleInt(num: number): number {
return num * num;
};
doubleInt(2);
// 4
doubleInt("hip hip");
// Error

When there is no return value, like when you’re just logging something to the console:

function printMsg(msg: string): void {
console.log(msg);
};

Just throw in void as the return type and you’re solid. And if you’re just converting an application to TypeScript and just trying to get setup, you may want to avoid breaking it right away and get used to the syntax or whatnot — you can also use any.

function printSomething(arg: any): void {
console.log(arg);
};
printSomething("the wheels on the bus...");
printSomething(false);

Obviously you won’t get any of the benefits of using TypeScript, but like mentioned maybe you’re just getting started, or you have a use-case that necessitates keeping it dynamic.

Enough with strings and numbers, what about other useful stuff?

var status: boolean = false;
// you can define the type and declare the variable's data simultaneously
toggleStatus();
// false --> true;
function checkStatus(): boolean {
return status;
};
checkStatus();
// true;

Alright, and what about arrays or lists? This is a bit more complicated because you have to consider what data types do you need/want in the array — will it be relatively static or quite dynamic and used for multiple occasions?

var employees: string[] = ["Mary", "John", "Kevin", "Gary"];
// this only requires a list of strings and can be restricted as such
var salaries: number[] = [75000, 92000, 113000, 51000];

These are very restrictive and can provide security and protection against unwanted data for these specified variables. I mean you wouldn’t want functions and methods working with these arrays of data to fail because it was expecting a number but received a string right?

Now in other languages you have tuples, which range in form, but it is a type of array — in TypeScript you can define what the type of each element will be. This implicitly means you are setting the length of the array too; the array can hold more than 2 elements.

var nyc: [string, number, boolean] = ["New York City", 8, false];

Alright alright, now objects. Let’s talk about objects with TypeScript now. There are a couple of things I want to touch upon briefly. Objects typically carry all types of data in it — just think of an external picture API returning JSON for an image and its information with links, the amount of likes it may have, the date it was uploaded and created or updated, etc etc.

One way to type check an object is to define an interface:

interface Image {
date: string,
links: string[],
likes: number,
private: boolean
}
function isShareable(img: Image) {
return !img.private;
};
// the ! (bang) will reverse the result

This is very handy for a number of reasons — you can check the parts of an object that will be used within your application and have that security and assurance. But this will also work even if the API updates the returned object with other properties and fields.

// API object
const imageResponse = {
date: "Wed Jan 4, 2015",
links: ["www.example.com/small", "www.example.com/medium", "www.example.com/large"]
likes: 238,
private: false,
description: null
}
interface Image {
date: string,
links: string[],
likes: number,
private: boolean
}
function isShareable(img: Image) {
return !img.private;
};
// will still work even though a new property is available and not defined with the interface

If the API removed the private property, then obviously this would lead to repercussions and the function(s) will fail!

https://basarat.gitbooks.io/typescript/docs/why-typescript.html

What’s also interesting about interfaces in TypeScript is that they can be merged when you define them multiple times; the second time does not overwrite the first declaration and definition.

interface City {
name: string,
state: string
}
interface City {
country: string,
tropic: boolean
}
// City now has 4 properties, including name and state

This is great for when you are utilizing an external library and you want to add onto it without trying to update the library itself or whatnot. And it can also be a way for a developer to not blow up the application while adding onto it for now and to go back and refactor/change if must be.

Another way to define and declare types is simpler and used for less complex situations.

https://basarat.gitbooks.io/typescript/docs/types/type-system.html

The single pipe | represents an OR scenario and is called a union type. You can use it like here with Text, or you can create a StrOrNum type:

https://basarat.gitbooks.io/typescript/docs/types/type-system.html

Or you could even do the following:

https://basarat.gitbooks.io/typescript/docs/types/type-system.html

There are scenarios where you may be working with multiple APIs and they may provide similar information but perhaps in different forms, or you would like a single function to handle different cases, and this is handy for when that time comes!

When it comes to statically-typed languages, casting is very popular — basically manually overriding or converting one type to another. In TypeScript it is known as Type Assertion.

The reason why it’s not called “type casting” is that casting generally implies some sort of runtime support. However, type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

Just like in Java, the syntax is very similar:

https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

But due to React and JSX, this syntax is a bit too similar and can be confusing — it is better to use “as” instead.

https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

Whether or not you use the original syntax or the as syntax, the compiler and TypeScript does not protect or guarantee you from ensuring you have all the properties defined. In the last example, foo is just an empty object. It can have a “bar” and “bas” property and their types are number and string, respectively. But they are not defined nor declared and there will be no reference to it in the transpiled or converted JavaScript after the compiling is completed.

In order to combat this:

https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

My first experience with statically-typed languages was with Java — I had to complete a code challenge for this company and they knew some of their candidates wouldn’t have prior knowledge of it but wanted to test their ability to quickly pick up another language and willingness to do so. It was very daunting at first, and you can check out a bit of that experience in a previous post. But what I love about TypeScript is that it is with JavaScript and you can customize and decide when, where and how to secure your application as it is not required to check for everything!

There is a lot to TypeScript and this is barely the tip of the iceberg apparently. I haven’t even actively coded in TypeScript just yet but am preparing and researching as I foresee myself needing it in the near future on my programming journey!

--

--

Paul Ly

Full-Stack Web Developer - Former JPM Analyst, ESL Teacher, and Expat