DEV Community

gagecantrelle
gagecantrelle

Posted on

The Basics of TypeScript

TypeScript - sounds familiar to another coding language called JavaScript, right? Well, it's a language based on JavaScript; the only difference is that it focuses on type safety. This makes it easier to catch errors before you run your code. This makes working on big projects easier to manage and improves the coding process by making it smoother and more reliable. Luckily, it's not too hard to learn as long as you have a basic understanding of JavaScript. JavaScript was created by Microsoft and released in October 2012

How do I start?
For starters, you need to install TypeScript as a developer(dev) dependency. If you're using Node.js, you must install the TypeScript node dependency as a dev dependency.

npm install typescript --save-dev
npm install @types/node --save-dev
npm install ts-node --save-dev
Enter fullscreen mode Exit fullscreen mode

When you declare a variable, you need to declare the value type. If you've created a variable called box that is a boolean, you will declare it as a boolean. You also need to do the same for the function and its parameters. Other types, like objects and arrays, need to be declared differently. Also, any TypeScript file name will need .ts(TypeScript) instead of .js(JavaScript) at the end of the name

var box: Noolean = true;
var obj = {n: Number}
let obj: Obj = {n: 1}
let arr: String[]
arr.push('test')

function checkbox(box: Boolean, {n}: {n: Number}): void{
if(box === true){
console.log(n)
}
}
checkbox(box, obj)
Enter fullscreen mode Exit fullscreen mode

But wait, there's more to know. If you want an array to hold different types, use this method

let test:  Array<string | number | boolean> = ["hello", 42, true];
Enter fullscreen mode Exit fullscreen mode

If your function returns a value, instead of saying void(returns no values), declare the return type

function str(): String {
return "hey this is a string"
}
Enter fullscreen mode Exit fullscreen mode

Then, depending on whether you plan to use a bundler like webpack, you need to install other dependencies. For some bundlers, like Next.js, you don't need to install any dependencies. Let's take a look at an example of Webpack using TypeScript.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  mode: 'development',
  stats: {
    excludeModules: /node_modules/,
  },
  entry: path.resolve(__dirname, './Client/index.tsx'),
  output: { filename: "bundle.js", path: path.join(__dirname, './Client/dist'),  publicPath: '/'},
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    plugins: [new TsconfigPathsPlugin()],
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx|js|jsx)$/,
        use: [{
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        },
        {
          loader: 'ts-loader',
          options: {
            transpileOnly: true,
          },
        },
      ],
      exclude: /node_modules/,
      },
    ]
  },  
  plugins: [
    new HtmlWebpackPlugin({template: path.join(__dirname, "./Client/index.html")}),
  ]
};
Enter fullscreen mode Exit fullscreen mode

What is a Tsconfig?
Now you're probably wondering what TsconfigPathsPlugin is? Well, it's a plugin that helps Webpack work with a TsConfig file. This is a file that tells TypeScript how to understand and then build your project. The TsconfigPathsPlugin is not needed, but can cause some TypeScript files to be compiled/built incorrectly if you don't use it. Let's take a look at what the TsConfig file would look like.

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "ES2022",
    "target": "es5",
    "allowJs": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
  }
}
Enter fullscreen mode Exit fullscreen mode

But what do all of those options do?

  • outDir: Puts all compiled JS files into a specific directory
  • noImplicitAny: Stop 'any' type from being used in the project
  • module: Tells how to use modules are handled (import/export) based on JavaScript standards(2022 standard)
  • Convert the code to work with older browsers that can only understand ES5
  • allowJs: mix TypeScript and JavaScript files together -moduleResolution: Tell TypeScript to look for modules like Node.js does (using node_modules)
  • allowSyntheticDefaultImports: Let you import default exports even if it not written properly for TypeScript
  • esModuleInterop: easyer inports from old commonJs module(import express from 'express')

There are plenty more options, but those 8 options are a good base for a default TsConfig file. If you want to know more about the other options, run this command in the terminal. It will create a default TsConfig file with all the options commented out. With each line describing what each option does. Now, some options won't be in the file when created, the reason being that they're advanced or rarely used.

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Example

  • type: Manually tells TypeScript which package to use( instead of making it guess like normal)
  • incremental: only rebuild changed files(make building faster)

@type/
Since TypeScript is a different language, any dependency you use will need to be compatible with it. Luckily, some dependencies have a TypeScript version. Let's take a look at the React version of TypeScript

npm install @types/react @types/react-dom --save-dev
///////////////////////////////////////////////////
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.1",
Enter fullscreen mode Exit fullscreen mode

Fun Fact 1: There is also an option for React in the TsConfig called jsx. This allows you to write JSX files in TypeScript.

jsx: "react-jsx"
Enter fullscreen mode Exit fullscreen mode

Fun Fact 2: You can't declare a React file with .jsx; it will need to be declared with .tsx at the end of the file name

That's it for the basics of TypeScript. If you find this blog helpful, leave a like and/or comment. Thanks for reading and have a nice day

Top comments (0)