@TOC
Introduction of TypeScript
What is a TypeScript?
- TypeScript is a free and open source programming language developed by Microsoft that is a superset of JavaScript.
- TypeScript extends JavaScript’s syntax so that any existing JavaScript program can work directly in TypeScript.
- TypeScript is designed for large-scale application development to ensure security and compatibility in production.
TypeScript VS JavaScript in depth comparison
- TypeScript and JavaScript are two of the most popular scripting languages in project development.
- TypeScript is a superset of JavaScript.
1. Key differences between JavaScript and TypeScript
-
TypeScript uses all of the code and coding concepts in JavaScript. TypeScript was created to make JavaScript development easier. For example, TypeScript uses concepts like types and interfaces to describe the data being used, which enables developers to quickly detect errors and debug applications
-
TypeScript extends the JavaScript object model both in terms of core language and in terms of molding class concepts. JavaScript code can work with TypeScript without modification, and a compiler can convert TypeScript code to JavaScript.
-
TypeScript provides compile-time static type checking through type annotations.
-
Data in TypeScript requires explicit typing; JavaScript does not.
-
TypeScript provides default parameter values for functions.
-
TypeScript introduces the concept of “classes” that are not found in JavaScript.
-
TypeScript introduces the concept of modules, which encapsulate declarations, data, functions, and classes.
2. The advantage of the TypeScript
-
Static input Static typing is a feature that can detect errors as developers write scripts. Finding and fixing bugs is a pressing need for today’s development teams. With this capability, developers will be able to write more robust code and maintain it for better quality and clarity.
-
Large development projects sometimes require small incremental changes to the code base in order to improve the development project. These small changes can have serious and unintended consequences, so it is necessary to reverse them. Refactoring is easier and faster using TypeScript tools.
-
Better collaboration When working on a large project, there are many developers, and the number of garbled characters and error machines increases. Type safety is a feature that detects errors during coding, not at compile time. This creates a more efficient coding and debugging process for the development team.
-
Factors such as cleaner ECMAScript 6 code, auto-completion and dynamic input help improve developer productivity. These features also help the compiler create optimized code.
3. The advantage of JavaScript
JavaScript also has some obvious advantages over TypeScript.
-
The community of popular JavaScript developers is still large and active, and it is easy to find a large number of mature development projects and available resources in the community.
-
The learning curve Due to the early and mature development of JavaScript, there are still a large number of developers who stick with the scripting language they are familiar with rather than learning TypeScript.
-
Native browser-enabled TypeScript code needs to be compiled (outputting JavaScript code), which is an additional step in TypeScript code execution.
-
No Need for Annotations To take advantage of TypeScript features, developers need to constantly annotate their code, which can make projects less efficient.
-
Flexibility Some developers prefer the flexibility of JavaScript.
4. Will JavaScript be replaced by TypeScript someday? (My humble opinion)
TypeScript is hot and good, but its weaknesses are obvious
- Some third-party JS libraries are missing DTS, or DTS updates are not timely. Can result in inconvenient use of it or calling outdated methods/functions
- For skilled front-end development, TypeScript can become a shackle. It forces you to write a bunch of verbose interface types. And some js ways are not compatible with it
- It also emasculates some of JS’s techniques.
Summary: I personally don’t want to close the window on learning about TypeScript, but I don’t think TypeScript will change the history of JavaScript the way JQuery did.
Install the TypeScript
TypeScript command-line tools are installed as follows:
npm install -g typescript
Copy the code
Compiling a TypeScript file is simple:
tsc hello.ts
Copy the code
We have a convention that files written in TypeScript end with.ts and React end with.tsx.
The editor
One of TypeScript’s greatest strengths is its enhanced editor and IDE capabilities, including code completion, interface hints, jump to definitions, refactoring, and more.
Major editors support TypeScript, and Visual Studio Code is recommended.
It is an open source, lightweight cross-terminal editor with built-in TypeScript support. It’s written in TypeScript itself.
Hello TypeScript
Copy the following code into hello.ts:
function sayHello(person: string) {
return 'Hello, ' + person;
}
let user = 'Tom';
console.log(sayHello(user));
Copy the code
Then perform
tsc hello.ts
Copy the code
A compiled file hello.js is generated:
function sayHello(person) {
return 'Hello, ' + person;
}
var user = 'Tom';
console.log(sayHello(user));
Copy the code
In TypeScript, use: to specify the type of a variable, with or without Spaces before and after:.
basis
This section introduces common types and some basic concepts in TypeScript to get you started on TypeScript. Specific contents include:
- Primitive data type
- Any value
- Type inference
- The joint type
- The type of the object — interface
- Array type
- Type of function
- Types of assertions
- Declaration file
- Built-in objects
Primitive data type
JavaScript comes in two types: Primitive data types and Object types. Primitive data types include: Boolean, numeric, string, NULL, undefined, and the new type Symbol in ES6. This section focuses on the use of the first five primitive data types in TypeScript.
Boolean In TypeScript, Boolean is used to define Boolean types:
let isDone: boolean = false;
// The compiler passes
// As a convention, code snippets that do not highlight compilation errors pass by default
Copy the code
Note that objects created using the constructor Boolean are not Booleans:
let createdByNewBoolean: boolean = new Boolean(1);
// Type Boolean cannot be assigned to type Boolean.
//'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible.
Copy the code
In fact, new Boolean() returns a Boolean object and calls Boolean directly. You can also return a Boolean type. In TypeScript, Boolean is a basic type in JavaScript, And Boolean is a constructor in JavaScript. The other basic types (except null and undefined) are the same
The numerical
Define numeric types using number:
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
// Binary representation in ES6
let binaryLiteral: number = 0b1010;
// Octal notation in ES6
let octalLiteral: number = 0o744;
let notANumber: number = NaN;
let infinityNumber: number = Infinity;
Copy the code
Compile result:
var decLiteral = 6;
var hexLiteral = 0xf00d;
// Binary representation in ES6
var binaryLiteral = 10;
// Octal notation in ES6
var octalLiteral = 484;
var notANumber = NaN;
var infinityNumber = Infinity;
Copy the code
String: Defines a string type using string:
let myName: string = 'Tom';
let myAge: number = 25;
// Template string
let sentence: string = `Hello, my name is ${myName}.
I'll be ${myAge + 1} years old next month.`;
Copy the code
Compile result:
var myName = 'Tom'; var myAge = 25; Var sentence = "Hello, my name is "+ myName + ". I'll be" + myAge + 1 + "years old next month.";Copy the code
Void values: JavaScript has no concept of Void values, but in TypeScript we can use Void to represent functions that do not return any value:
function alertName() :void {
alert('My name is Tom');
}
Copy the code
Declaring a void variable doesn’t help much, because you can only assign it to undefined and null:
let unusable: void = undefined;
Copy the code
Null and Undefined in TypeScript, Null and Undefined are used to define these two primitive data types:
let u: undefined = undefined;
let n: null = null;
Copy the code
The difference with void is that undefined and null are subtypes of all types. Variables of type undefined can be assigned to variables of type number:
// This will not report an error
let num: number = undefined;
// No error will be reported
let u: undefined;
let num: number = u;
Copy the code
Void variables cannot be assigned to variables of type number:
let u: void;
let num: number = u;
// Type 'void' is not assignable to type 'number'.
Copy the code
Any value
An arbitrary value (Any) is used to indicate that assignments of Any type are allowed.
If it is a common type, it is not allowed to change the type during assignment:
let myFavoriteNumber: string = 'seven';
myFavoriteNumber = 7;
// index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
Copy the code