Signup/Sign In

How to transition your web application to TypeScript

Posted in Programming   AUGUST 25, 2022

    Transition your web application to TypeScript

    Do you know why developers use TypeScript for Web Development? TypeScript is used to make JavaScript development more efficient and it helps to catch errors earlier that's why it is considered "JavaScript and more".

    TypeScript can play a big role in development but do you already have a Web application developed in JavaScript? then how would you convert it into a TypeScript application?

    Don't worry, here are some techniques that you can use to implement TypeScript in your application. let's learn more about what is TypeScript and How does it work.

    What is TypeScript?

    TypeScript is an object-oriented, strongly typed, compiled programming language that is a superset of JavaScript. It builds on top of JavaScript.

    It means that you write some code in TypeScript then you compile that TypeScript code into a plain JavaScript code with the help of a TypeScript Compiler.

    When you compile the TypeScript and have the JavaScript code, you can deploy it to environments where JavaScript runs.

    Where is TypeScript used?

    • It is used to introduce types of JavaScript

    • It helps to find errors

    • It makes the code more efficient

    • It implements planned features of future JavaScript.

    Installing TypeScript and Webpack

    If you are using React then you can easily create a new project using create-react-app's TypeScript template.

    npx create-react-app --template typescript

    If you can do this then you can skip the rest of the steps.

    If you are not using React then you'll need to install TypeScript manually as a development dependency.

    npm install --save-dev typescript

    If you want to use the CLI then you can also install TypeScript globally on your machine.

    TypeScript files are saved using .ts extension and you can compile the programs using tsc. Try running the following command on your machine:

    function Hello(object: string) {
      console.log(`Hello, ${object}!`);
    }
    
    Hello('World')

    As I said above, compile the code using tsc:

    tsc test.ts

    You can run tsc with -w flag which builds whenever the program changes. Integrate it with Webpack as part of the build process, you can install Webpack using npm:

    npm install --save-dev webpack webpack-cli

    To store your compiler settings, you will need to create a new file for TypeScript Configuration at tsconfig.json.

    {
        "compilerOptions": {
            "outDir": "./dist/",
            "sourceMap": true,
            "skipLibCheck": true,
            "noImplicitAny": true,
            "module": "commonjs",
            "target": "es6",
            "jsx": "react"
        }
    }

    Now, you'll create webpack.config.json or modify if it exists to resolve TypeScript extensions and use tsloader. Now, turn on source maps for enhanced debugging.

    module.exports = {
        mode: "production",
    
        // Enable sourcemaps for debugging webpack's output.
        devtool: "source-map",
    
        resolve: {
            // Add '.ts' and '.tsx' as resolvable extensions.
            extensions: [".ts", ".tsx"]
        },
    
        module: {
            rules: [
                {
                    test: /.ts(x?)$/,
                    exclude: /node_modules/,
                    use: [
                        {
                            loader: "ts-loader"
                        }
                    ]
                },
                // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
                {
                    enforce: "pre",
                    test: /.js$/,
                    loader: "source-map-loader"
                }
            ]
        },
    
        // When importing a module whose path matches one of the following, just
        // assume a corresponding global variable exists and use that instead.
        // This is important because it allows us to avoid bundling all of our
        // dependencies, which allows browsers to cache those libraries between builds.
        externals: {
            "react": "React",
            "react-dom": "ReactDOM"
        }
    };

    Run webpack or webpack-dev-server to handle the loading of TypeScript files automatically.

    How To Work With JS-Based Packages

    All JavaScript libraries don't support TypeScript but third-party types are available from DefinitelyTyped which is a community repository. It maintains typings for common libraries like React. You can install them as npm dependencies. You can install React like this:

    npm install --save-dev @types/react @types/react-dom

    If you are having compiler errors after installing any new package then try to install @types/package.

    Some packages don't have publically available types, you can fix the typings by writing a declaration file for it. The declaration file is saved as package.d.ts in your src and the file looks like this:

    export as namespace Package
    export = Package
    
    declare namespace Package {
      interface Type {
        value: boolean
      }
      // etc...
    }

    Then you can use the declaration by adding a reference at the top of any code using that package:

    ///<reference path="package.d.ts"/>

    How To Type Legacy Code

    Typing legacy code takes time according to the size of your project. Typing legacy code involves creating custom interfaces for the values that are passed and returned by the functions you've implemented.

    See below, a React that contains a React component that renders some JSX:

    Legacy code 1

    You can use a new interface so the function can use that interface. You'll need to add it to the interface along with the corresponding type whenever you reference a key on props in the code.

    Legacy code 2

    you'll need to define props.divCustomColor or an error will occur when you use this function in another file.

    If you can't figure out what to do then you can use ts-ignore flag to disable TypeScript compiler warnings or you can use ts-nocheck for an entire file.

    //@ts-ignore

    Adding Project-Wide Types

    You'll need to create a global declaration file to add custom types project-wide. If you want to create a referenceable enum storing your app's colors then you can save the following in your src folder as global.d.ts.

    declare global {
        enum Color {
            primary = "#6ca583",
            accent = "#9b8dab",
        }
    }
    
    export {};

    About the author:
    Proficient in Java, Python, and web development; has a knack for writing clearly about complex topics. Dedicated to giving readers the tools they need to learn more about computer science and technology.
    Tags:javascriptweb-developmenttypescript
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS