Common TypeScript File Features And Errors

There are plenty of TypeScript files you may need to work on within a project. Each of them comes with plenty of unique features you should pay attention to, and we are going to introduce them to you in this guide.

Import A Type From Another File Using TypeScript

Prior to version 3.8, you can import a type using the import statement. But since this version, TypeScript also supports explicit type-only exports and imports. This allows you to tell the compiler you are expecting a type from another module.

To export a type:

export type {};

To import that type in another TypeScript file:

import type {} from ;

For example, you can define and export an object type in module1.js:

export type Site = {
    name: string;
    domain: string;
};

In other files, you can then import this type like this:

import { Site } from './module1';
const home: Site = {
    name: "LearnShareIT",
    domain: "learnshareit.com"
};

Remember that this syntax with the extra type keyword will be removed from the compiled JavaScript code. These declarations will be only used for declarations and annotations, with no remnant at runtime.

How To Generate A tsconfig.json File

The tsconfig.json file contains compilation options required by your project. The TypeScript compiler comes with an option to generate it. Run this command in the root directory of your project:

tsc –init

This isn’t the only option. You can also manually create a file named tsconfig.json and fill in its content later.

How To Run A TypeScript File From The Command Line

TypeScript is just a superset of JavaScript. You will need to compile them to JavaScript code before running your TypeScript files.

tsc is the official compiler for TypeScript:

tsc yourfile.ts

The compiler will compile your file into JavaScript with the same name (yourfile.js). You can then run it with runtime environments like Node.js:

node yourfile.js

How To Read A File’s Contents In TypeScript

You can use the fs module of Node.js to read the contents of text files. This module comes with many methods for file system interactions using POSIX functions.

First, you will need to install type definitions for Node.js:

npm install @types/node

This is an example of using the readFile() method to read the text file output.txt with TypeScript:

import { readFile } from "node:fs";
readFile('output.txt', 'utf8', function(err, data){
    console.log(data);
});

Output

LearnShareIT

Here we specify UTF-8 as the encoding system, and the callback function after reading the content is to print it.

How To Write To A File Using TypeScript

In a similar manner, you can use the fs.writeFile() method to write to a file in your local file system.

import { writeFile } from "node:fs";
const content = "Welcome to our website";
writeFile("output.txt", content, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("Content successfully written to file\n");
    }
});

Output

Content successfully written to file

In this example, our callback function will print errors if they happen during the writing operation. Otherwise, a confirmation message will be displayed.

How To Parse A JSON String In TypeScript

JSON is a standard built-in object that provides methods for reading and writing JSON sources. In particular, the JSON.parse() method can parse a JSON string and return a value or object from its content.

The simple syntax of this method:

JSON.parse(text)

You will need to provide the raw text content you need to parse as JSON. The method will return a string, boolean, number, Array, Object, or null value depending on that JSON text.

To provide the source, you can use the fs.readFile() method above to read it from a file. This is how you can use the JSON.parse() in TypeScript to read a JSON file and convert it to an object:

import { readFile } from "node:fs";
readFile('data.json', 'utf8', function(err, json){
    let data = JSON.parse(json);
    console.log(data);
    console.log(typeof data);
});

Output

{ name: 'John', age: 23, gender: 'male', title: 'Senior Engineer' }
object

As you can see, the JSON.parse() method returns an object representing the JSON source stored in the data.json file. You can then manipulate it like any other TypeScript object.

Import A Javascript File Into A TypeScript File

TypeScript code can import and work with your existing JavaScript files.

First, make sure your project supports JavaScript by enabling the allowJS option in its configuration file. Ensure the tsconfig.json file has this line in the compilerOptions section:

    "allowJs": true,

If the file doesn’t exist, create an empty file named tsconfig.json and add this content to it:

{
  "compilerOptions": {
    "allowJs": true,
  }
}

You can then use the import statement to use JavaScript files as inputs in your TypeScript project.

For example, you can define and export a function from a JavaScript file:

export function total(a, b) {
    return a + b;
};

Then import it from your TypeScript project:

import { total} from './javascript.js';
console.log(total(3, 5));

Output

8

File Name Differs From Included File Name Only In Casing

TypeScript is compatible with plenty of case sensitivity rules, depending on the operating system it is running on. This allows this language to work with many platforms.

However, sometimes this versatility becomes problematic when developers from case-sensitive and case-insensitive file systems collaborate.

For instance, you will need to use this statement when you want to import the module.ts file:

import * from "./module";

However, you will see this error when you also have a file named Module.js file in the same place:

Already included file name ‘module.ts’ differs from file name ‘Module.ts’ only in casing.

The best solution for this problem is to make sure you don’t have similar file names whose only differences are the letter cases. Rename Module.ts to something else, such as module1.ts.

How To Ignore Errors In TypeScript Files

Since version 2.6, TypeScript allows you to suppress errors with // @ts-ignore. The compiler will ignore all the errors caused by the next code line when you place the above comment before it.

For example, this line of code will normally result in an error:

const order: number = "1";

Output

Type 'string' is not assignable to type 'number'

You have explicitly set number as the type for the variable order, but you assign a string value to it at the same time. The compiler will notice this disparity and raise an error.

However, it will compile just fine if you add @ts-ignore above it:

const order: number = "1";
console.log(order);

Additionally, the // @ts-nocheck comment was added in TypeScript 3.7 to expand this ability to the whole file. Developers of TypeScript support it to make migrations from JavaScript easier since this comment is available in JavaScript too.

Tutorials

Learn more about TS Files in the article below:

Summary

Features of TypeScript files may work in a different way compared to how they do in JavaScript. You should be aware of these differences, including new features only available in TypeScript.

Leave a Reply

Your email address will not be published. Required fields are marked *