Alim's Blog

πŸŽ‰Hello, welcome to my blog!πŸŽ‰

Find me on

Learning TypeScript as a JavaScript Developer: Chapter 1 (Introduction)

08 Sep 2023|6 MIN READ

When I first learned JavaScript, one thing gave me immense pleasure that is I can define a variable without writing its type. It gave me the same vibe as writing python codes. In js, after initializing a variavle let a = 5 we can assign it like a = 'Hello' that is, in the same variable we can assign values of different types. This might be looking interesting in the first place but while developing a large application it might produce unexpected behavior. Let me talk about another example. Have a look at the following code snippet:

function add(a, b) {
  return a + b;
}

In the function written above expects two numbers as parameter & returns their summation. While calling it, if instead of two numbers two strings or one number & one string is passed, the function will not return any error rather it will return the concatenation of both which means add('hello', 1) will return hello1 as output. This is not the behavior we were expecting. In most cases our goal here will be getting the summation of two numbers. One handy solution to this problem can be using static type checking which will allow only numbers as parameters of this function. Let me present another code snippet to you.

function manipulateString(inputString) {
  const uppercaseString = inputString.toUpperCase();
  const resultString = `HELLO: ${uppercaseString}`;
  return resultString;
}

The function written above expects a string as its parameter & returns HELLO followed by its capitalized version like manipulateString('guys') will return HELLO GUYS. Now if we pass something other than a string like number then the function will return error like SyntaxError because toUpperCase() is a built in function for string not for other types. So the function manipulateString will always expect a string as its input.

The two cases I have explained above clearly demonstrates some limitations of JavaScript which can be eliminated by using TypeScript very easily. TypeScript is an open source, object oriented, strongly typed programming language developed & maintained by microsoft. According to the official document:

TypeScript is JavaScript with syntax for types.

TypeScript has been developed as a wrapper on JavaScript along with strong typed checking, OOP support & some other features. So we can say that all JavaScript are TypeScript but all TypeScript are not JavaScript. TypeScript comes with a compiler named TSC which is TypeScript Compiler that does static type checking & also converts ts into js because browsers cannot understand TypeScript. Whenever any application is built with TypeScript, it needs to be compiled to JavaScript before being deployed or run locally. TypeScript compiler is installed when we install TypeScript in our machine. In order to create a TypeScript project we need to write tsc --init in our terminal which will create a tsconfig.json file. This file contains necessary configurations for TypeScript to be implemented to that project. A typical tsconfig.json file can look like following:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "ESNext",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ESNext'. */
    "module": "CommonJS",                     /* Specify module code generation: 'None', 'CommonJS', 'AMD', 'System', 'UMD', 'ES6', 'ES2015', 'ES2020', 'ES2022', 'ESNext'. */
    "outDir": "./dist",                       /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    /* Additional Checks */
    "noUnusedLocals": true,                   /* Report errors on unused locals. */
    "noUnusedParameters": true,               /* Report errors on unused parameters. */
    /* Module Resolution Options */
    "esModuleInterop": true,                  /* Emit __importStar and __importDefault helpers for runtime Babel ecosystem compatibility and enable --allowSyntheticDefaultImports for typesystem compatibility. */
    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
    /* Output Options */
    "declaration": true,                     /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "outFile": "./dist/index.js",            /* Concatenate and emit output to a single .js file. */
    /* Project References */
    "composite": true,                       /* Enable project references. */
    /* Experimental Options */
    "incremental": true,                    /* Enable incremental compilation, which reuses the results of a previous compilation to save time. */
  },
  "include": ["src/**/*.ts"],               /* Specify an array of glob patterns that match TypeScript files to be included in the compilation. */
  "exclude": ["node_modules"]               /* Specify an array of glob patterns that match files and directories to be excluded from the compilation. */
}

As a beginner we don't need to go to the details of each of those but while developing a large application those configurations may need to be changed accordingly. Now lets try to solve the two problems I mentioned earlier with TypeScript. TypeScript brings a new level of structure and predictability to your code, making it especially valuable in larger applications or collaborative projects. Let's delve deeper into how TypeScript solves these issues.

One of TypeScript's standout features is its strong static type system. With TypeScript, you can explicitly define the types of variables, function parameters, and return values. This means you can catch type-related errors during development rather than at runtime. For example, if you try to pass a string to a function that expects a number, TypeScript will raise a compile-time error, alerting you to the issue before you even run your code. In the case of the add function, TypeScript ensures that only numbers can be used as arguments, preventing unintended concatenation or other unexpected behavior. This type safety not only reduces runtime errors but also makes your code more self-documenting and easier for other developers to understand. So the updated type safe functions will look like following:

function add(a: number, b: number): number {
  return a + b;
}

function manipulateString(inputString: string): string {
  const uppercaseString = inputString.toUpperCase();
  const resultString = `HELLO: ${uppercaseString}`;
  return resultString;
}

TypeScript also enhances the development experience by providing better tooling support in modern code editors and integrated development environments (IDEs). When you write TypeScript code, your editor can provide real-time feedback, offer auto-completions, and display type-related hints, making your coding process more efficient and error-free.

Another crucial aspect of TypeScript is its compiler (tsc). This tool not only checks your code for type-related issues but also compiles your TypeScript files into plain JavaScript. Browsers cannot execute TypeScript directly, so the compilation step is necessary. The tsconfig.json file, which you configure during project setup, guides the TypeScript compiler in how to transpile your code, ensuring compatibility with your target environment.

In conclusion, TypeScript extends the capabilities of JavaScript by introducing static typing, enabling better tooling support and providing a smooth compilation process. As you continue your journey through this TypeScript series, you'll explore various TypeScript features and best practices that will empower you as a JavaScript developer to write more robust and maintainable code. Stay tuned for Chapter 2, where we'll dive deeper into TypeScript's type system.

Happy Learning πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€

Buy Me A Coffee

Share this on

Go back to home page

Created by M A Alim