This article first appeared on my personal blog :

The case code has been uploaded to TypeScript

TypeScript It's not a completely new language , It is JavaScript Superset , by JavaScript The ecology of nature has increased the type mechanism , And finally compile the code into pure JavaScript Code .

TypeScript brief introduction

TypeScript from Microsoft( You count Angular 2 If you want to add Google) Develop and maintain an open source programming language . It supports JavaScript All the syntax and semantics of , At the same time, by acting as ECMAScript To provide some extra functionality , Such as type detection and richer Syntax . The image below shows TypeScript And ES5,ES2015,ES2016 The relationship between .

Use TypeScript Why

JavaScript It's a weak type language , The data type of variable is dynamic , The type of the variable can only be determined at execution time , This kind of hindsight error recognition method will make developers become debugging masters , But it's not good for programming , It also reduces development efficiency .TypeScript The type mechanism of can effectively eliminate the misuse problem caused by variable type , And developers can control the level of type monitoring , Strictly restricted variable type or loosely restricted variable type , It all depends on the developer's development needs . After adding the type mechanism , There are two main side effects : Increase the learning curve of developers , Increase the development time of setting type . Overall speaking , These costs are relative to the robustness and maintainability of the code , It's all worth it .

Besides , The type annotation is TypeScript One of the built-in features of , Allow text editors and IDE Better static analysis of our code . This means that we can use the help of automatic compilation tools , Reduce errors when writing code , So as to improve our productivity .

Yes TypeScript Here's a brief introduction to , Next, a brief summary of its unique knowledge points ,( Many online tutorials actually put ES6, ES7 The knowledge points are also included in ts The knowledge of , Of course, that's right ~)

data type

String type

A text that holds strings , The type is declared as string. You can find that type declarations can be uppercase or lowercase , The following is the same .

let name: string = 'muyy'
let name2: String = 'muyy'
Boolen type

boolean yes true or false Value , therefore let isBool3: boolean = new Boolean(1) It will compile and report errors , because new Boolean(1) What is generated is a Bool object .

let isBool1: boolean = false
Number type
let number: number = 10;
Array type

An array is Array type . However , Because an array is a collection , We also need to specify the type of elements in the array . We go through Array<type> or type[] Syntax to specify the type of an element in an array

let arr:number[] = [1, 2, 3, 4, 5];
let arr2:Array<number> = [1, 2, 3, 4, 5]; let arr3:string[] = ["1","2"];
let arr4:Array<string> = ["1","2"];
Enums type

List all available values , The default initial value of an enumeration is 0. You can adjust the initial range :

enum Role {Employee = 3, Manager, Admin}
let role: Role = Role.Employee
console.log(role) // 3
Any type

any It's the default type , A variable of its type allows any type of value :

let notSure:any = 10;
let notSure2:any[] = [1,"2",false];
Void type

JavaScript There is no null value Void The concept of , stay TypeScirpt in , It can be used void Represents a function that does not have any return value :

function alertName(): void {
console.log('My name is muyy')


Define a type for a function

We can add a type to each parameter and then add a return value type to the function itself . TypeScript It can automatically infer the return value type according to the return statement , So we usually omit it . The following function add, add2, add3 The effect is the same , Where is add3 Function is the complete type of function .

function add(x: string, y: string): string{
return "Hello TypeScript";
} let add2 = function(x: string, y: string): string{
return "Hello TypeScript";
} let add3: (x: string, y: string) => string = function(x: string, y: string): string{
return "Hello TypeScript";
Optional and default parameters

JavaScript in , Each parameter is optional , Can pass but not pass . When I didn't pass the reference , Its value is undefined . stay TypeScript We can use it next to the parameter name ? Realize the function of optional parameters . such as , We want to make lastname It's optional :

function buildName(firstName: string, lastname?: string){
console.log(lastname ? firstName + "" + lastname : firstName)
} let res1 = buildName(" singing "," people "); // Naruto
let res2 = buildName(" singing "); // singing
let res3 = buildName(" singing ", " people ", " jun "); // Supplied parameters do not match any signature of call target.

If a parameter with a default value appears before a required parameter , The user must explicitly pass in undefined Value to get the default value . for example , Let's rewrite the example , Give Way firstName Is a parameter with a default value :

function buildName2(firstName = " singing ", lastName?: string){
console.log(firstName + "" + lastName)
} let res4 = buildName2(" people "); // undefined people
let res5 = buildName2(undefined, " people "); // Naruto


Conventional JavaScript Programs use functions and prototype based inheritance to create reusable components , But it's a bit tricky for programmers who are familiar with the object-oriented approach , Because they use class based inheritance and objects are built from classes . from ECMAScript 2015, That is to say ECMAScript 6 Start ,JavaScript Programmers will be able to use a class based object-oriented approach . Use TypeScript, We allow developers to use these features now , And compiled JavaScript Can run on all major browsers and platforms , You don't have to wait until the next JavaScript edition .

class Person{
name:string; // This is right The definition of type
constructor(name:string,age:number){ = name;
this.age = age;
return + this.age;
} let person:Person = new Person('muyy',23)
console.log(person.print()) // muyy23

When we refer to any class member, we use this. It means that we are accessing members of the class . In fact, this is essentially ES6 Knowledge , It's just ES6 More on the basis of this Type declarations for fields and reference parameters .

class Person{
public name:string; // public、private、static yes typescript Class access modifiers in
constructor(name:string,age:number){ = name;
this.age = age;
console.log( + this.age);
} class Student extends Person{
this.gender = gender;
console.log( + this.age + this.gender);
} var student = new Student("male");
student.tell(); // muyy23male

This example shows TypeScript Some of the features inherited in the book , As you can see, it's also ES6 And type declaration . But here's one more point of knowledge —— public , private , And protected modifiers .TypeScript in , Members default to public ; When a member is marked as private when , It can't be accessed outside the class that declares it ;protected Embellishments and private The behavior of the modifier is very similar , But it's a little different ,protected Members are still accessible in derived classes .


TypeScript Supported by getters/setters To intercept access to object members . It can help you effectively control access to object members .

For accessors, there are the following points to pay attention to :

First , Accessor requires you to set the compiler to output ECMAScript 5 Or higher . Demotion to... Is not supported ECMAScript 3. secondly , Only with get Without set The accessor of is automatically inferred as readonly. This is generating... From code .d.ts Documents are helpful , Because users who use this property will see that they are not allowed to change its value .

class Hello{
private _name: string;
private _age: number;
get name(): string {
return this._name;
set name(value: string) {
this._name = value;
get age(): number{
return this._age;
set age(age: number) {
if(age>0 && age<100){
console.log(" Age 0-100 Between "); // Age 0-100 Between
this._age = age;
} let hello = new Hello(); = "muyy";
hello.age = 23
console.log(; // muyy



TypeScript One of the core principles of is to type check the structure of a value . stay TypeScript in , The purpose of an interface is to name these types and define contracts for your code or third-party code .

interface LabelValue{
label: string;
} function printLabel(labelObj: LabelValue){
} let myObj = {
"label":"hello Interface"

LabelledValue Interface is like a name , It represents that there is a label Property and type is string The object of . As long as the incoming object satisfies the above necessary conditions , So it's allowed .

in addition , The type checker does not check the order of properties , As long as the corresponding attribute exists and the type is right .

Optional attribute

Interfaces with optional properties are similar to normal interface definitions , Just add a... After the optional attribute name definition ? Symbol . One of the benefits of optional attributes is that you can pre define the attributes that might exist , The second advantage is that you can catch errors when referring to non-existent properties .

interface Person{
} function printInfo(info:Person){
} let info = {
}; printInfo(info); // {"name": "muyy", "age": 23} let info2 = {
}; printInfo(info2); // {"name": "muyy"}
Function type

Interfaces can describe JavaScript The various shapes that objects have in . In addition to describing ordinary objects with properties , Interfaces can also describe function types . The defined function type interface is like a function definition with only parameter list and return value type . Each parameter in the parameter list needs a name and type . After definition, after completion , We can use the interface of this function type just like any other interface .

interface SearchFunc{
(source: string, subString: string): boolean;
} let mySearch: SearchFunc;
mySearch = function(source: string,subString: string){
return !== -1;
}; console.log(mySearch(" Naruto "," singing ")); // true
console.log(mySearch(" Naruto "," Tassel ")); // false
Indexable type

It's similar to using interfaces to describe function types , We can also describe those who can “ Get... By index ” The type of , such as a[10] or ageMap["daniel"]. An indexable type has an index signature , It describes the type of object index , And the corresponding index return value type . Let's look at the following example :

interface StringArray{
[index: number]: string;
} let MyArray: StringArray;
MyArray = [" yes "," cloud "," along with "," wind "];
console.log(MyArray[2]); // along with
Class types

And C# or Java The basic function of the interface is the same ,TypeScript It can also be used to explicitly force a class to conform to a contract .

We can describe a method in the interface , Implement it in a class , Like the following setTime The method is the same :

interface ClockInterface{
currentTime: Date;
setTime(d: Date);
} class Clock implements ClockInterface{
currentTime: Date;
setTime(d: Date){
this.currentTime = d;
constructor(h: number, m: number) {}
Inherited interface

Like the class , Interfaces can also inherit from each other . This allows us to copy members from one interface to another , The interface can be more flexibly divided into reusable modules .

interface Shape{
color: string;
} interface PenStroke{
penWidth: number;
} interface Square extends Shape,PenStroke{
sideLength: number;
} let s = <Square>{};
s.color = "blue";
s.penWidth = 100;
s.sideLength = 10;


TypeScript And ECMAScript 2015 equally , Any containing top level import perhaps export Files are treated as a module .

export interface StringValidator{
isAcceptable(s:string): boolean;
} var strReg = /^[A-Za-z]+$/;
var numReg = /^[0-9]+$/; export class letterValidator implements StringValidator{
isAcceptable(s:string): boolean{
return strReg.test(s);
} export class zipCode implements StringValidator{
isAcceptable(s: string): boolean{
return s.length == 5 && numReg.test(s);


In Software Engineering , We don't just have to create consistent, well-defined API , Also consider reusability . Component can not only support the current data type , It can also support future data types , This provides you with very flexible features when creating large systems .

In image C# and Java In such a language , You can use generics to create reusable components , A component can support multiple types of data . In this way, users can use components with their own data types .

Explore generics

The following code , We give Hello Function adds a type variable T ,T Help us capture the type of user input ( such as :string). We put this version of Hello Functions are called generics , Because it can be applied to multiple types . In the code output and output2 Yes, the effect is the same , The second method is more common , Using type inference —— That is, the compiler will automatically help us to determine T The type of :

function Hello<T>(arg:T):T{
return arg;
} let outPut = Hello<string>('Hello Generic');
let output2 = Hello('Hello Generic') console.log(outPut);

Reference material

from JavaScript To TypeScript More articles about

  1. from JavaScript To TypeScript series

    With the development of applications , In the project JavaScript Our code will be more and more bloated , At this time many JavaScript The abuse of language will become more and more obvious , and TypeScript Appearance , Is to focus on solving JavaScript language ...

  2. JavaScript and TypeScript Intersections —— Type definition file (*.d.ts)

    stay < from JavaScript To TypeScript series > The article we have learned TypeScript Relevant knowledge . TypeScript The core of this is static types , We're writing TS When ...

  3. JavaScript and TypeScript Medium class

    For a front-end Developer , Rarely use class , Because in JavaScript There's more to it than Functional expression Programming , Raise your hand is a function, It's almost gone class or new The trace of . therefore Design patterns It's also big ...

  4. JavaScript、TypeScript、ES6 The connection and difference between the three

    ES6 What is it? ECMAScript 6.0( hereinafter referred to as ES6) yes JavaScript Language ( Now it's time to follow ES5 standard ) The next generation of standards , Already in 2015 year 6 It was officially released in April . Its goal , Is making JavaScript Language can ...

  5. JavaScript and TypeScript The difference and connection

    Reprinted from : JavaSc ...

  6. Web Essentials And JavaScript,TypeScript and CoffeeScript

    return Web Essentials Function catalog some Javascript Functions can also be used for TypeScript. This directory function Smart tips TypeScript CoffeeScript function JSHint J ...

  7. typedi Powerful javascript as well as typescript Dependency injection framework

    typedi yes typestack Dependency injection solutions provided by the team , about typescript We can use the annotation development approach , The official documents are also quite detailed javascript Use Function based service injection var Ser ...

  8. JavaScript 、TypeScript Medium Boolean

    boolean yes JavaScript An interesting raw data type in . stay TypeScript in , Non strict mode ("strictNullChecks": false), It's allowed in total 4 It's worth ...

  9. [ translate ] TypeScript Getting started (JavaScript Superset )

    Have you ever heard of TypeScript? TypeScript yes JavaScript Superset ,TypeScript A combination of type checking and static analysis , Explicit interface .TypeScript It's Microsoft's open source project , It is from C# The father of ...

Random recommendation

  1. jsp Error configuring project Deployment failure on Tomcat 6.x. Could not copy all resources to

    from : There was a problem in deploying the project online today tomcat It's never been deployed Check it on the Internet Write down the reasons for you to see Deplo ...

  2. fdtd simulation, plotting with gnuplot, writting in perl

    # 9 month 13 Japan In Huanglongxi, Chengdu 1 #!/usr/bin/perl # Author : Leon Email: # fdtd simulation , plo ...

  3. install Exchange2010

    1.exadmin Add to Schema admins,enterprise admins In the group CAS,HUB,MB install .Net Framework CAS,HUB:2.Run 'ServerManag ...

  4. UVa 1643 Angle and Squares

    The question : Pictured , Yes n A square and a corner ( All in the first quadrant ), Make these squares and this corner form a closed shadow area , Find the maximum area of the shadow area . analysis : intuitively , When this n When the diagonal of a square is in a straight line , The enclosed area is the largest .( ...

  5. Android Studio Gradle project refresh failed No such property classpath for class

    New one android The project actually found that it couldn't run ,gradle Can't start , strange : Gradle 'Meitian' project refresh failed:          No such p ...

  6. About NSString and NSMutableString Related usage and basic introduction of

    Objective-C The core class that handles strings in is NSString And NSMutableString , The biggest difference between these two classes is NSString After the assignment is created, the content and length of the string cannot be changed dynamically , Unless it's heavy ...

  7. D - Dice Game (BFS)

    A dice is a small cube, with each side having a different number of spots on it, ranging from 1 to 6 ...

  8. Talk about npm Dependency management

    introduction Now the front-end development is almost inseparable from nodejs Package manager npm, For example, the front-end is used to build local development services and package and compile front-end code . In front end development , Frequently used npm install To install the required dependencies , As for the technology ...

  9. Vue2.1.7 Source code learning

    The original name of the article is < The source code parsing >, But think about it later , Or use it “ Source code learning ” It's a little more appropriate , Without a thorough grasp of every letter in the source code ,“ analysis ” It's a bit of a headline party . Before reading this article , It's better to turn on 2.1.7 Source code for ...

  10. luoguP3750 [ The joint examination of six provinces 2017] Break up is a wish Probability expectation DP + greedy

    ........... It's really divine , I can't think about it ................... Choose... For the exam $50$ Be greedy +$15$ Split pressure , Give up the rest ........ Make $f[i]$ From the smallest step ...