SoFunction
Updated on 2025-03-04

Analysis of the difference between TypeScript and JavaScript

TypeScript is an open source programming language developed by Microsoft, built by adding static type definitions based on JavaScript. Due to the limitations of the JavaScript language itself, it is difficult to be competent for the development and maintenance of large-scale projects. Therefore, Microsoft developed TypeScript, making it competent for the development of large-scale projects. TypeScript is translated into JavaScript code through the TypeScript compiler or Babel, and can run in any browser or any operating system.

TypeScript can use all the code and programming concepts in JavaScript, and TypeScript is created to make JavaScript development easier. It is recommended to learn TS first while being proficient in JS, which is more conducive to learning two languages ​​at the same time.

TypeScript Advantages

TypeScript has many benefits compared to JavaScript.

TS makes code refactoring easier and emphasizes explicit types, allowing developers to master the way various components interact. Because it supports compile-time debugging, it has some benefits for teams dealing with large and complex applications.

Setting up TypeScript for any project is easy. Some frameworks, such as Angular, use TypeScript by default. So, TypeScript seems to me to be better.

When should I migrate my project to TypeScript?

TypeScript can be used when the code size, complexity and error rate increase and when specific problems need to be determined during the compilation process.
TypeScript also has interfaces and access modifiers that allow developers to collaborate and interact on a single code base. Therefore, it is best to use TypeScript at the beginning of the project.
But if you like frameworks like or such, you won't like TypeScript, the first choice for these frameworks is JavaScript.

The difference between TypeScript and JavaScript

TypeScript is a superset of JavaScript that extends the syntax of JavaScript, so existing JavaScript code can work with TypeScript without any modifications. TypeScript provides compile-time static type checking through type annotations.

TypeScript can process existing JavaScript code and compile only the TypeScript code in it.

TS is generally used for large-scale projects, just like the underlying library of WeChat applets is implemented using TS, while the WeChat applet itself, the application layer, is implemented using JS.

Complexity is a key factor to consider.JavaScript is perfect for simpler applications because it runs on all platforms (cross-platform) and is very lightweight. In addition, compiling TS code with the time and CPU resources is more troublesome for the project than the minimum overhead of JS.

TypeScript is actually typed JavaScript. It not only supports all the features of JavaScript, but also adds static type annotation extensions based on JavaScript. In a sense, TypeScript is actually a superset of JavaScript. In TypeScript, we can not only easily reuse JavaScript's code and latest features, but also use optional static types to check for errors, making the code written more robust and easier to maintain. For example, in the development stage, we can quickly eliminate many low-level errors (such as typo, types, etc.) through the TypeScript code translator.

TypeScript basic syntax

At the syntax level, the default type annotation TypeScript is exactly the same as JavaScript. Therefore, we can think of writing TypeScript code as adding type annotations to JavaScript code. In TypeScript syntax, type annotation is mainly achieved through type post-synchronization.

let num = 1;

The syntax in the example conforms to both JavaScript syntax and TypeScript syntax. The difference between TypeScript syntax and JavaScript syntax is that we can explicitly declare the variable num in TypeScript that is just a numeric type, that is, just add the: number type annotation after the variable num

let num: number = 1;

TypeScript original type

In JavaScript, primitive types refer to non-object and no method data types. They include six types: string, number, bigint, boolean, undefined and symbol (null is a pseudo-primitive type, which is actually an object in JavaScript, and all structured types are derived from the null prototype chain). In the JavaScript language, the original type value is the lowest implementation, and it corresponds to the lowest type in TypeScript.

1. String

In JavaScript, we can use string to represent any string in JavaScript (including template strings)

let firstname: string = 'Captain'; // String literallet familyname: string = String('S'); // Explicit type conversionlet fullname: string = `my name is ${firstname}.${familyname}`; // Template string

2. Numbers

The number type represents decimal integers, floating-point numbers, as well as binary numbers, octal numbers, and hexadecimal numbers that JavaScript has already supported or will be supported.

/** Decimal integer */

let integer: number = 6;

/** Decimal integer */

let integer2: number = Number(42);

/** Decimal floating point number */

let decimal: number = 3.14;

/** Binary integer */

let binary: number = 0b1010;

/** Octal integer */

let octal: number = 0o744;

/** Hexadecimal integer */

let hex: number = 0xf00d;

/** If you use fewer large integers, then we can use the bigint type to represent */

let big: bigint = 100n;

3. Boolean value

boolean means True or False

/** TypeScript is really fragrant for real */

let TypeScriptIsGreat: boolean = true;

/** TypeScript is too bad for No */

let TypeScriptIsBad: boolean = false;

Primitive Type

We can create a unique tag through the Symbol constructor

let sym1: symbol = Symbol();

let sym2: symbol = Symbol('42');

Of course, TypeScript also includes types such as Number, String, Boolean, Symbol, etc. (note that it is case sensitive).

let sym: symbol = Symbol('a');

let sym2: Symbol = Symbol('b');

sym = sym2 // ok or fail?

sym2 = sym // ok or fail?

let str: String = new String('a');

let str2: string = 'a';

str = str2; // ok or fail?

str2 = str; // ok or fail?

In fact, we can't use the Number, String, Boolean, Symbol types at all because they have no special purpose. This is like we don't have to use JavaScript Number, String, Boolean and other constructors new for a corresponding instance.

{
let mustBeNum = 1;
}

{
let mustBeNum: number = 1;
}

Below, we will make some modifications to the above example

{
let mustBeNum = 'badString';
}

{
let mustBeNum: number = 'badString';
}

If the context in which the variable is located is particularly complex, the ability to detect low-level type errors at the development stage will be particularly important, and this ability mainly comes from static type detection implemented by TypeScript.

5. Static type detection

During the compilation period, statically typed programming languages ​​can accurately detect type errors, which is the advantage of static type detection. During the compilation (translation), the TypeScript compiler will check whether there is an error in the type of the detected variable's received value with the type of the display annotation. If the two types are exactly the same, the detection will be passed; if the two types are inconsistent, it will throw a compilation period error to inform us of the encoding error. The specific example is shown in the following code:

const trueNum: number = 42;

const fakeNum: number = "42";

// ts(2322) Type 'string' is not assignable to type 'number'.

TypeScript reference types

1.Array

Because the arrays and tuples of TypeScript are all arrays after being translated into JavaScript, we will integrate the two types of arrays and tuples together to introduce them, which will also facilitate your better comparison and learning.

2.Array type (Array)

In TypeScript, we can also define array types like JavaScript and specify the type of array elements.

/** child elements are arrays of numeric types */

let arrayOfNumber: number[] = [1, 2, 3];

/** child elements are arrays of string types */

let arrayOfString: string[] = ['x', 'y', 'z'];

3. Tuple type (Tuple)

The most important feature of a tuple is that it can limit the number and type of array elements, which is particularly suitable for implementing multi-valued return. One scenario we are familiar with using tuples is React Hooks (for an introduction to React Hooks, please click here to view), for example, the useState example:

import { useState } from 'react'

function useCount() {

const [count, setCount] = useState(0);

return ....;

}

4. any

any refers to an arbitrary type, which is an official cheating method that selectively bypasses static type detection. We can do anything on variables annotated as type any, including obtaining properties and methods that do not actually exist, and TypeScript cannot detect whether their properties exist and whether the type is correct. For example, we can assign any type of value to variables of type any type, or assign any type of value to variables of any type (except never), as shown in the following code:

let anything: any = {};

(); // No errors are prompted
anything = 1; // No errors are prompted
anything = 'x'; // No errors are prompted
let num: number = anything; // No errors are prompted
let str: string = anything; // No errors are prompted

5. unknown

unknown is a type added in TypeScript 3.0. It is mainly used to describe variables with undefined types. For example, in multiple if else condition branch scenarios, it can be used to receive temporary variables of different types of return values ​​under different conditions, as shown in the following code:

let result: unknown;

if (x) {

result = x();

} else if (y) {

result = y();

} ...

6. void、undefined、null

After much consideration, we decided to integrate void, undefined and null "three wastes" special types together to introduce them. According to official statements, they are not actually very useful, especially in the strict mode that is highly recommended and required in this column, which is veritable "bord". First let's talk about the void type, which is only suitable for functions that represent no return value. That is, if the function does not return a value, its type is void. In strict mode, declaring a void type variable has little practical use, because we cannot assign the void type variable value to any type variable except any and unkown. Then let's talk about undefined types and null types, which are the only two exceptions for TypeScript values ​​with the same name as the type keyword. But this does not affect their being called "boring", because simply declaring undefined or null variables is also extremely useless, as the example is as follows:

let undeclared: undefined = undefined; // Abandoned
let nullable: null = null; // Abandoned

The greatest value of undefined is mainly reflected in the interface type, which represents a default and undefined property. Here I share a slightly puzzling design: we can assign undefined value or variable with type undefined to void type variables. Conversely, variables with type void but value undefined cannot be assigned to undefined type.

const userInfo: {

id?: number;

} = {};

let undeclared: undefined = undefined;

let unusable: void = undefined;

unusable = undeclared; // ok

undeclared = unusable; // ts(2322)

I think the value of null is mainly reflected in interface formulation, which indicates that the object or attribute may be null values. Especially for interfaces that interact with front and back ends, such as Java Restful and Graphql, any attributes and objects involving queries may be null empty objects, as shown in the following code:

const userInfo: {

name: null | string

} = { name: null };

7. never

never means a type of value that will never occur. Here we will give an actual scenario to illustrate. First, we define a function that throws errors uniformly. The code example is as follows:

function ThrowError(msg: string): never {

throw Error(msg);

}

Since the above function will never have a return value, its return value type is never. Similarly, if there is a dead loop in the function code, the return value type of this function is never, as shown in the following code.

function InfiniteLoop(): never {

while (true) {}

}

never is a subtype of all types, and it can assign values ​​to all types, as shown in the following code.

let Unreachable: never = 1; // ts(2322)

Unreachable = 'string'; // ts(2322)

Unreachable = true; // ts(2322)

let num: number = Unreachable; // ok

let str: string = Unreachable; // ok

let bool: boolean = Unreachable; // ok

8. object

The object type represents a type that is not a primitive type, that is, a type that is not a number, string, boolean, bigint, symbol, null, and undefined. However, it is also a type that has no use, and one of the application scenarios shown below is the type used to represent.

declare function create(o: object | null): any;

create({}); // ok

create(() => null); // ok

create(2); // ts(2345)

create('string'); // ts(2345)

TypeScript type detection cannot achieve absolute intelligence, after all, programs cannot think like humans. Sometimes we encounter situations where we are more clear about the actual types than TypeScript, such as the following example:

const arrayNumber: number[] = [1, 2, 3, 4];

const greaterThan2: number = (num => num > 2);

// hint ts(2322)

summary

TypeScript is actually JavaScript with type annotations added, and it has no subversive changes. Therefore, learning and mastering TypeScript will definitely be an extremely easy task.

This is the article about the difference between TypeScript and JavaScript. For more information about the difference between TypeScript and JavaScript, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!