Intersection & Union Types (Intersection and Union Types)

0 20
Translator: Yang Bing, JD RetailTranslated from the article on the Radix website...

Translator: Yang Bing, JD Retail

Translated from the article on the Radix website, original link:
https://radixweb.com/blog/typescript-vs-javascript,Original author: Nihar Raval

Intersection & Union Types (Intersection and Union Types)

1678168740_6406d2a418dadeec75ed9.png!small?1678168740942


Looking for an experienced JavaScript development team to bring your application ideas to life? As a developer, if you have the opportunity to participate in a web development project, you must understand the working principles of JavaScript. JavaScript has been on the market for many years and has become a popular scripting language in the developer community.

But as we know, if a technology or language is rising, there will always be another choice entering the market and competing fiercely with the leaders. Here is a new competitor - TypeScript. With the increasing popularity of TypeScript, we can consider it as an enhanced version of JavaScript with additional features.

When it comes to TypeScript, it is an open-source programming language used for developing large and complex applications. TypeScript was developed by one of the technology giants, Microsoft, in 2012, and the real reason behind its creation was to handle large applications.

In addition, Angular also uses TypeScript for web development services. According to this study, TypeScript and JavaScript are the second and third most popular languages that developers wish to use. Do you know why?

In fact, JavaScript is considered to be the main scripting language for applications and web pages. Therefore, now, we can use JavaScript with front-end frameworks such as TezJS and React, as well as with back-end frameworks such as Node.Js and Deno.

But the real question now is, was JavaScript developed to create large and complex web applications? I think the answer is no!

In this article, we will compare these two programming languages - TypeScript and JavaScript, their relationship, their differences, and outline the advantages of each language.

But before that, let's quickly understand the differences between TypeScript and JavaScript in this video.

1678168754_6406d2b22938d05e4ae4c.png!small?1678168755410


The real difference between TypeScript and JavaScript

If we consider both of them at the same time - TypeScript and JavaScript, then every JavaScript code is valid in TypeScript. This means that TypeScript is a superset of JavaScript.

In other words, we can say that

JavaScript + more features = TypeScript

Therefore, if you save a JavaScript programming file (.js) as a TypeScript (.ts) extension, it will perform very well. But this does not mean that these two languages - TypeScript and JavaScript - are the same.

Therefore, before we delve deeper, let's first understand the basic definitions of each language. The following data is from Google Trends and shows the search trends of these two front-end languages over the past year.

1678168764_6406d2bc52877d9562682.png!small?1678168764776


Why develop TypeScript when JavaScript is already available?

The JavaScript language was introduced as a client-side programming language. But as JavaScript is used in web development, developers have realized that it can also be considered as a server-side programming language.

However, JavaScript code has also become quite complex and heavy. Therefore, JavaScript cannot meet the expectations of an object-oriented programming language. Therefore, JavaScript will never flourish as a server-side technology in the industry. This is why the TypeScript language was born to bridge this gap.

What is TypeScript?

If you are asked 'What is better than JavaScript?' you will definitely get the answer - TypeScript.

TypeScript is developed and maintained by Microsoft and is an open-source programming language that is object-oriented. It is a superset of JavaScript, including optional types. In addition, it can be compiled into pure JavaScript.

In short, TypeScript is a statically compiled programming language used to write clear and concise JavaScript code. It achieves the same purpose as JavaScript and can be used for client and server-side applications. In addition, JavaScript libraries are also compatible with TypeScript.

1678168800_6406d2e09f8601f814819.png!small?1678168801428

TypeScript is a programming language that supports both dynamic and static types. It provides classes, visibility scope, namespaces, inheritance, union, interfaces, and many other features. In addition, it also provides comments, variables, statements, expressions, modules, and functions.

You can run it on Node.Js or any other browser that supports ECMAScript 3 or its latest version.

Since TypeScript is an enhanced version of JavaScript, all JavaScript code is syntactically valid TypeScript. However, this does not mean that the TypeScript compiler can handle all JavaScript:

let a = 'a'; a = 1; // throws: error TS2322: Type '1' is not assignable to type 'string'.

The files provided by TypeScript can include type data from the current target file, similar to how C++ header files define the creation of the current target file. Therefore, other applications can use the values defined in the file, just like using static type values of TypeScript entities.

You will also find third-party header files for popular libraries (such as jQuery, D3.js, and MongoDB). There are also TypeScript headers for NodeJs basic modules, allowing Node.Js development in TypeScript.

The TypeScript compiler is assembled in JavaScript and written in TypeScript. It is registered under the Apache License 2.0.

After watching the TypeScript introduction, you must be wondering what the purpose of adding static types to JavaScript is?

Alright, we can use the given statements to clarify your doubts:

  • You can avoid hidden ninja errors, such as the classic 'undefined' is not a function.
  • It is easy to refactor code without significantly damaging it.
  • Locating oneself in large and complex systems is no longer a nightmare.

According to this study, TypeScript identifies about 15% of JavaScript errors.

The freedom of dynamic types often leads to errors, which not only reduces the efficiency of developers but also makes development more cumbersome due to the increased overhead of adding new lines of code.

Therefore, due to the lack of type and compile-time error checking, JavaScript is a poor choice for server-side code in organizations and large codebases.

As their slogan suggests, TypeScript is an extensible JavaScript.

Why do we need to use TypeScript?

As we mentioned earlier, TypeScript is an enhanced version of JavaScript. Therefore, when comparing it with other languages such as CoffeeScript (which adds syntactic sugar) or PureScript (which is completely different from JavaScript), a lot needs to be learned to write TypeScript code.

1678168815_6406d2ef7390bf241cba0.png!small?1678168815989


In TypeScript, types are optional, and any JavaScript file is a valid TypeScript file. Although if there are any type issues in your initial files, the compiler will notify you, it will still provide a valid JavaScript file. TypeScript will not disappoint and it is also very simple to improve your skills over time.

Is TypeScript suitable for front-end or back-end?

Since TypeScript is compiled into JavaScript, it is suitable for both front-end and back-end application development.

In addition, JavaScript is the preferred programming language for the front-end of web pages and applications. Therefore, for the same reason, TypeScript may be used, but it is also suitable for complex large enterprise projects on the server side.

But you can also use other top-level front-end frameworks (such as React, Angular, Vue) to build the next generation of applications.

TypeScript types

TypeScript includes various basic types, such as Number, Array, Tuple, Boolean, String, and so on. Well, some of these types are not available in JavaScript. However, you can learn more about them in the TypeScript documentation.

In addition, there are some other types that are expressive in TypeScript:

Any & Unknown

A type named Any (any type you want) can cover unknown as its type-safe system. Here, any allows you to assign and use JavaScript variables when you want to escape the type system. It is widely used to describe incoming variables that have not been verified and are of unknown type (such as those from third-party APIs).

Unknown is similar to Any, but it does not allow you to perform any operations on it unless it has been explicitly type-checked.

Void

Use Void when there is no return value. It is generally used as the return type of functions that do not return anything.

Never

Never is the return type for things that should not happen, such as exception throwing functions.

Intersection & Union Types (Intersection and Union Types)

These types allow you to create custom types based on logic.

Intersection types allow you to combine several basic types into one type. For example, if we create a custom type Person that contains first_name: string and last_name: string. Well, you can say: I want my typeThis and that.

Union types allow you to input one of various basic types. For example, if there is a function that returns result: string or undefined, you can say: I want my typeThis or that.

When you view them as spaces, all these types make sense.

1678168833_6406d301a6006f73afe42.png!small?1678168834332


TypeScript supports both implicit and explicit types. If you do not explicitly write types, the compiler will enable type inference to identify the type you are using.

On the other hand, explicitly writing them brings benefits, such as assisting other team members in reading your code and verifying that what you see is what the compiler sees.

Characteristics of TypeScript

With the advanced features of TypeScript, it supports additional features of JavaScript, such as object-oriented programming concepts, JS libraries, platform independence, etc.

Compatibility (Compatibility)

TypeScript also supports both old and new additional features. However, it is compatible with all versions of JavaScript, such as ES7 and ES12. It can compile complete code from ES7 back to ES5, and vice versa. This ensures a smooth transition and language portability.

Static Typing (Static Typing)

Static typing means that developers must declare variable types.

Suppose we take the variable name str. The code will not run until you give it a type, such as Integer, Float, List, or any other type. And TypeScript is statically typed.

Static typing can help you detect errors early and complete code faster, etc.

Now, let's provide you with other outstanding features here:

  • It is easy to maintain and can improve project productivity.
  • Static typing and comments can be used.
  • Supports object-oriented features such as interfaces, inheritance, and classes
  • Debugging is simple, and problems are discovered early.
  • Supports ES6 (ECMAScript), which provides a simpler syntax for handling objects and inheritance.
  • Full-featured IDE support

Advantages of TypeScript

TypeScript provides a variety of advantages that can help you write better programming languages for web development.

Language Features (language features)

The following are other features supported by TypeScript.

  • Namespaces
  • Interfaces
  • Null Checks
  • Generics
  • Access Modifiers

Optional Parameters (optional parameters)

// -- TypeScript -- //
function log(message: string = null) { }
// -- TypeScript compiled output -- //
function log(message) {
if (message === void 0) { message = null; }
}
// -- JavaScript with Babel -- //
function Log(message = null) { }
// -- Babel compiled output -- //
"use strict";
function Log() {
var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
}

Classes Class methods

// -- TypeScript -- //
class Article {
name: string;
constructor(name: string) {
this.name = name;
}
}
// -- TypeScript compiled output -- //
var Article = /** @class */ (function () {
function Article(name) {
this.name = name;
}
return Article;
}());
// -- JavaScript with Babel -- //
class Article {
constructor(name) {
this.name = name;
}
}
// -- Babel compiled output -- //
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Article = function Article(name) {}}
_classCallCheck(this, Article);
this.name = name;
};

What is JavaScript?

JavaScript - a scripting language used to develop interactive web pages. It follows client-side programming rules; therefore, it can be executed seamlessly in the user's web browser. However, you can use JavaScript in combination with other technologies (such as XML and REST API).

The main purpose of JavaScript is to make it a complementary scripting language, similar to Visual Basic to C++. However, JavaScript is not suitable for large and complex applications. It is intended to write only a few hundred lines of code for an application.

The following are some unique features provided by JavaScript:

  • Flexible, dynamic, and cross-platform
  • It can be used on both client and server sides
  • Lightweight Parsing
  • All browsers support it
  • Weak Typing
  • Just-in-time Compilation

Differences between TypeScript and JavaScript

Differences between TypeScript and JavaScript
When comparing two programming languages - TypeScript and JavaScript, we must consider many factors, as shown below:

1) Learning Curve

TypeScript is a superset of JavaScript. To write TypeScript code, you should have a basic understanding and knowledge of JavaScript. In addition, you should be clear about the concept of OOPS.

On the other hand, JavaScript is a popular and easy-to-learn scripting language. Many developers use JavaScript in combination with CSS and HTML to create web applications. However, HTML is difficult because it includes event handling, web behavior, animation, and scripts.

2) Developer Community

TypeScript has gained popularity in a short period of time and has been implemented by many enterprises. You can find many tutorials and guides on the Internet to learn TypeScript. However, it has a very active and supportive community.

On the other hand, compared to TypeScript, JavaScript does not have a large community. JavaScript provides many libraries, frameworks, and coding practices. Therefore, it is recommended that you understand the web development team structure that is most suitable for your business needs to achieve overall team performance.

3) Performance

It is widely known that TypeScript was created to overcome the challenges of JavaScript for large and complex applications. Therefore, TypeScript saves development time and makes developers more efficient.

The only difference between TypeScript and JavaScript is that TypeScript code is compiled into JavaScript before execution.

4) Syntax

TypeScript provides variable declarations, functional paradigms, and a type system that JavaScript does not provide. It is syntactically similar to JScript and .Net, supporting ECMAScript 2015 standard features, including modules, arrow function syntax, and classes.

JavaScript also follows the ECMAScript definition. However, it is not a typed language like TypeScript. It uses many structured programming terms from the C language, such as if statements, switch statements, do-while loops, and so on. It provides event-driven style, functional, and imperative programming.

5) Tools and Frameworks

Due to Microsoft's support for TypeScript, it has many leading frameworks and editors. Through tight integration with editors, it provides error handling during compilation to avoid errors at runtime.

On the other hand, there are many JavaScript frameworks available in the market for web development projects. This is a vast ecosystem that is very popular among programmers. You can quickly find developers proficient in ReactJS, VueJS, Angular, and other frameworks.

6) Code

For TypeScript:

class Person
{
private name: string;
constructor (private name: string)
{
this.name = name;
}
name()
{
return "name is " + this.name;
}
}

For JavaScript:

var Person = (function()
{
function Person(personName)
{
this.name = personName;
}
Person.prototype.name = function()
{
return "My name is " + this.name;
}
return Person;
})();

What is the difference between TypeScript and JavaScript?

We know that TypeScript offers more features than JavaScript. In short, TypeScript is an object-oriented programming language, while JavaScript is a scripting language. Therefore, TypeScript provides interfaces and modules through ES6 features; on the other hand, JavaScript does not provide such features.

Actually, some developers may confuse object-oriented and functional programming languages. However, you can distinguish between functional programming and object-oriented programming languages here, and understand the differences between them.

Why migrate your project to TypeScript?

If you have a large and complex codebase, the likelihood of errors occurring is higher. However, it would be great if some errors could be resolved during compilation. At this point, you can use TypeScript to reduce compile-time errors. The best part is that a complete JavaScript codebase can be reused as is.

When to choose: The difference between JavaScript and TypeScript

TypeScript

Compile-time type checking

Using Vanilla JavaScript, type verification is performed at runtime. However, this increases runtime overhead, which can be avoided by performing compile-time verification.

Large projects or multiple developers

TypeScript can run seamlessly in large projects or when many developers work together.

Easy to use new libraries or frameworks

Assuming that if you are developing with React and are not familiar with its API, you can get grammar hints to help you identify and navigate the new interface. However, they all provide type definitions

JavaScript

Small projects

For small projects with less code, TypeScript may be a bit overkill.

Framework support

If TypeScript does not support the framework you have chosen - for example EmberJS, you may not be able to utilize its features.

Build tools

To generate executable final JavaScript, TypeScript needs to have a build step. However, developing JavaScript applications without using any build tools is becoming less common.

Test workflow

If your excellent JavaScript developer is already using test-driven development, the benefits of switching to TypeScript may not be enough to justify the migration cost.

Should I learn JavaScript or TypeScript?

If you understand JavaScript, it will be easy for you to understand TypeScript. They share the same syntax and runtime behavior.

As the most popular language, JavaScript provides many resources and a vast developer community. Since both languages often execute in the same way in many cases, TypeScript developers can also benefit from these resources.

Advantages of TypeScript over JavaScript

  • TypeScript supports static typing. This means that static typing allows for type accuracy to be checked at build time.
  • During development, TypeScript will identify compilation errors. Therefore, the scope of runtime evaluation errors is very small. On the other hand, JavaScript is an interpreted language.
  • TypeScript is just JS with some additional features, i.e., ES6 features. The TS compiler can compile .ts files into ECMAScript, although it may not be stored in the web browser you choose.

Will TypeScript replace JavaScript?

So, the shortest answer to the above question is no!

When talking about TypeScript, it is a completely different language, but it inherits the basic properties of JavaScript. Therefore, JavaScript will never be replaced.

JavaScript is one of the popular foundational technologies in the software development industry, used extensively by developers for both client and server-side.

On the other hand, TypeScript does not execute directly in web browsers. It is translated into JavaScript. JavaScript is easier to debug and compile because it executes directly in web browsers. However, TypeScript is not developed for all types of projects. Therefore, both programming languages have their advantages, disadvantages, and a set of features. To keep up with the trends of corporate web development, you must adopt new technologies or frameworks to obtain better business processes and customer experiences.

Positive comparison: TypeScript vs JavaScript

TypeScript and JavaScript have many similarities in developing interactive web pages. When providing a direct comparison between TypeScript and JavaScript, we can say that JavaScript is a lightweight interpreted dynamic language used to enhance HTML web pages. On the other hand, TypeScript is an enhanced version of JavaScript. This means that TypeScript is a combination of JavaScript and some other features.

  • TypeScript is an object-oriented programming language developed by Microsoft Corporation, while JavaScript is a programming language used for the Web.
  • TypeScript is an open-source language for building large-scale web applications, while JavaScript is a server-side programming language that helps develop interactive web pages.
    On the other hand, TypeScript is an enhanced version of JavaScript. This means that TypeScript is a combination of JavaScript and some other features.Let's understand the important differences between TypeScript and JavaScript in the table below.

Scope

Typescript

JavaScript

Developers

Microsoft in 2012

Brendan Eich (Netscape), 1995

Definition

TypeScript is a powerful object-oriented language, as a superset of JavaScript, with generics and JS features to solve complex JavaScript problems.

JavaScript is a scripting language with top-notch features for creating dynamic web pages.

Types

Strong typing. TypeScript supports both static and dynamic typing.

Weak typing. JavaScript only supports dynamic typing.

Ecosystem

TypeScript is more like a powerful and intuitive language that supports static typing.

JavaScript is a simple language that optimizes code compatibility, making it easy to read and write.

Compilation

TypeScript requires compilation.

JavaScript does not require compilation.

Data binding

TypeScript uses concepts such as interfaces and types to define the data used.

There is no such concept in JavaScript.

Learning curve

TypeScript has an unfriendly learning curve. In addition, it requires knowledge of JavaScript.

It is easy to learn and a flexible language for writing Web scripts.

Npm packages

With TypeScript, many npm packages either have static type definitions or have an easier external type definition to install.

JavaScript provides an alternative to search and generate code without any build steps.

Client-side or server-side

TypeScript is specifically used for the client-side.

JavaScript is used for both server-side and client-side.

File extensions

.tsx and .ts

.js

Community

TypeScript has a smaller community of software developers.

JavaScript has a large community of software developers.

Prototype design

Prototype design features are available in TypeScript.

JS does not support prototype design.

Companies and websites

Asana, Clever, Screen award

Airbnb, Codecademy, Instagram

Code Example

function multiply (a, b){ return a*b;}var result = multiply(a, b);console.log('The answer is - ' + result);

<script>function multiply (a, b){ return a*b;}var result = multiply(a, b);document.write ('The answer is – ' + result);</script>

Conclusion

Finally, after reading all the insights we have sorted out in this article, we can say that both languages have their pros and cons.

TypeScript is suitable for developers who want to create clean and readable code. Well, we haven't mentioned what TypeScript provides, including various real-time error checks and static types.

Although JavaScript is not an all-encompassing programming language, it can be used with HTML to improve the quality of web pages. Even, you will find many experienced developers who are proficient in JavaScript coding.

However, like JavaScript, not all web browsers support TypeScript. So, if you are hesitating between TypeScript and JavaScript, you can refer to the article above.


This is the first translation, and my level is limited. Please feel free to point out any inappropriate translations by experts.

你可能想看:
最后修改时间:
admin
上一篇 2025年03月30日 10:55
下一篇 2025年03月30日 11:17

评论已关闭