from JavaScript to TypeScript
TypeScript is not a completely new language, it is a superset of JavaScript, adds a type mechanism to the ecology of JavaScript, and eventually compiles the code into purely JavaScript code.
TypeScript Introduction
TypeScript is an open source programming language developed and maintained by Microsoft (plus Google for Angular 2). It supports all the syntax and semantics of JavaScript while providing some additional functionality, such as type detection and richer syntax, as a superset of ECMAScript. Shows the relationship between TypeScript and es5,es2015,es2016.
Reasons for using TypeScript
JavaScript is a weak type of language, the data type of the variable is dynamic, only the execution of the variable type can be determined, this posterior perception of the mistaken method will let developers become debugging master, but not conducive to the improvement of programming ability, but also reduce development efficiency. The type mechanism of the TypeScript can effectively eliminate misuse problems caused by variable types, and developers can control the degree to which the type is monitored, whether the variable type is strictly restricted or the type of the loose restriction variable, depending on the developer's development needs. After adding the type mechanism, there are two main side effects: increasing the developer's learning curve and increasing the development time of the set type. Overall, these efforts are worthwhile relative to the robustness and maintainability of the code.
In addition, type annotations are one of the built-in features of TypeScript, allowing text editors and Ides to perform better static analysis of our code. This means that we can improve our productivity by reducing errors when writing code with the help of automated compilation tools.
The introduction of TypeScript to this, next to its unique knowledge points for a brief summary, (online many tutorials actually put ES6, ES7 knowledge point also counted into TS knowledge point, of course this is right ~)
Data type String type
A text that holds a string that is declared as String. You can find that the type declaration can be uppercase or lowercase, and then the same.
let name: string = 'muyy'let name2: String = 'muyy'
Boolen type
Boolean is the value of true or false, so let Isbool3:boolean = new Boolean (1) compiles an error because the new Boolean (1) generates a Bool object.
let isBool1: boolean = false
Number Type
let number: number = 10;
Array type
The array is of type array. However, because the array is a collection, we also need to specify the type of elements in the array. We specify types by array<type> or type[] syntax for elements within 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
Lists all available values, and the default initial value for an enumeration is 0. You can adjust the start range:
enum Role {Employee = 3, Manager, Admin}let role: Role = Role.Employeeconsole.log(role) // 3
Any type
Any is the default type, and variables of its type allow values of any type:
let notSure:any = 10;let notSure2:any[] = [1,"2",false];
Void type
JavaScript does not have the concept of NULL void, in TYPESCIRPT, you can use void to represent a function that does not have any return value:
function alertName(): void { console.log('My name is muyy')}
function defines a type for a function
We can add a type to each parameter and then add the return value type to the function itself. Typescript is able to infer the return value type automatically based on the return statement, so we usually omit it. The following function add, ADD2, add3 effect is the same, where the 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 parameters and default parameters
In JavaScript, each parameter is optional and can be passed through. When there is no reference, its value is undefined. In TypeScript, we can use it next to the parameter name. The ability to implement optional parameters. For example, we want to make LastName optional:
function buildName(firstName: string, lastname?: string){ console.log(lastname ? firstName + "" + lastname : firstName)}let res1 = buildName("鸣","人"); // 鸣人let res2 = buildName("鸣"); // 鸣let res3 = buildName("鸣", "人", "君"); // Supplied parameters do not match any signature of call target.
If the parameter with the default value is in front of the required parameter, the user must explicitly pass in the undefined value to get the default value. For example, let's rewrite the example so that FirstName is a parameter with a default value:
function buildName2(firstName = "鸣", lastName?: string){ console.log(firstName + "" + lastName)}let res4 = buildName2("人"); // undefined人let res5 = buildName2(undefined, "人"); // 鸣人
Class
Traditional JavaScript programs use functions and prototype-based inheritance to create reusable components, but it's tricky for programmers who are familiar with object-oriented methods because they use class-based inheritance and objects are built from classes. Starting with ECMAScript 2015, or ECMAScript 6, JavaScript programmers will be able to use class-based object-oriented approaches. Using Typescript, we allow developers to use these features now, and compiled JavaScript can run on all major browsers and platforms without waiting for the next JavaScript version.
Class
class Person{ name:string; // 这个是对后文this.name类型的定义 age:number; constructor(name:string,age:number){ this.name = name; this.age = age; } print(){ return this.name + this.age; }}let person:Person = new Person('muyy',23)console.log(person.print()) // muyy23
We use this when referencing any one of the class members. It indicates that we are accessing members of the class. In fact, this is essentially a ES6 of knowledge, only on the basis of ES6 on the This field and the reference parameter of the type declaration.
Inherited
class Person{ public name:string; // public、private、static 是 typescript 中的类访问修饰符 age:number; constructor(name:string,age:number){ this.name = name; this.age = age; } tell(){ console.log(this.name + this.age); }}class Student extends Person{ gender:string; constructor(gender:string){ super("muyy",23); this.gender = gender; } tell(){ console.log(this.name + this.age + this.gender); }}var student = new Student("male");student.tell(); // muyy23male
This example shows some of the traits inherited in TypeScript, and you can see that it is also ES6 knowledge plus a type declaration. But here's a bit more of a knowledge point--public, private, and protected modifiers. TypeScript, the member defaults to public, and when the member is marked private, it cannot be accessed outside the class that declares it; the protected modifier behaves much like the private modifier, but with a little difference, protected Members can still be accessed in derived classes.
Memory
TypeScript supports the interception of access to object members through Getters/setters. It can help you effectively control access to object members.
There are a few things to note about accessors:
First, the accessor requires that you set the compiler to output ECMAScript 5 or higher. Downgrading to ECMAScript 3 is not supported. Second, only accessors with a get without set are automatically inferred as ReadOnly. This is helpful when generating a. d.ts file from code, because the user using this attribute will see that it is 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("年龄在0-100之间"); // 年龄在0-100之间 return; } this._age = age; }}let hello = new Hello();hello.name = "muyy";hello.age = 23console.log(hello.name); // muyy
Interface interface
One of the core principles of typescript is the type checking of the structure of the value. In typescript, the role of an interface is to name these types and define contracts for your code or for third-party code.
interface LabelValue{ label: string;}function printLabel(labelObj: LabelValue){ console.log(labelObj.label);}let myObj = { "label":"hello Interface"};printLabel(myObj);
The Labelledvalue interface is like a name that represents an object that has a label property and is of type string. As long as the incoming object satisfies the necessary requirements, it is allowed.
In addition, the type checker does not check the order of attributes, as long as the corresponding property exists and the type is correct.
Optional properties
An interface with optional attributes is similar to a normal interface definition, except for an optional attribute name definition. Symbol. One of the benefits of an optional attribute is the ability to pre-define a possible property, and the second benefit is that you can catch an error that references a property that does not exist.
interface Person{ name?:string; age?:number;}function printInfo(info:Person){ console.log(info);}let info = { "name":"muyy", "age":23};printInfo(info); // {"name": "muyy", "age": 23}let info2 = { "name":"muyy"};printInfo(info2); // {"name": "muyy"}
function type
The interface can describe the various shapes that objects in JavaScript have. In addition to describing ordinary objects with attributes, an interface can also describe a function type. The defined function type interface is like a function definition with only a parameter list and a return value type. Each parameter in the argument list requires a name and type. After the definition is complete, we can use the interface of this function type as with other interfaces.
interface SearchFunc{ (source: string, subString: string): boolean;}let mySearch: SearchFunc;mySearch = function(source: string,subString: string){ return source.search(subString) !== -1;};console.log(mySearch("鸣人","鸣")); // trueconsole.log(mySearch("鸣人","缨")); // false
indexable types
Similar to the use of interfaces to describe function types, we can also describe types that can be "indexed", such as a[10] or agemap["Daniel". An indexed type has an index signature that 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 = ["是","云","随","风"];console.log(MyArray[2]); // 随
Class type
Like the basic role of interfaces in C # or Java, TypeScript can also use it to explicitly force a class to conform to some kind of contract.
We can describe a method in an interface that implements it in a class, as in the following settime method:
interface ClockInterface{ currentTime: Date; setTime(d: Date);}class Clock implements ClockInterface{ currentTime: Date; setTime(d: Date){ this.currentTime = d; } constructor(h: number, m: number) {}}
Inheriting interfaces
Like classes, interfaces can inherit from each other. This allows us to copy members from one interface to another, allowing for more flexibility in dividing the interface 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;
Module
TypeScript and ECMAScript 20,151, any file containing top-level import or export is 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); }}
Generic type
In software engineering, we not only create consistent, well-defined APIs, but also consider reusability. Not only does the component support the current data type, but it also supports future data types, which provides you with very flexible functionality when creating large systems.
In languages such as C # and Java, generics can be used to create reusable components, and one component can support multiple types of data. This allows the user to use the component with their own data type.
Preliminary study on generics
In the following code, we add a type variable t to the Hello function, and T helps us to capture the type that the user passed in (for example, string). We call this version of the Hello function generic, because it can be applied to more than one type. The output and Output2 in the code are the same, and the second method is more common, using type inference-that is, the compiler automatically helps us determine the type of T based on the parameters passed in:
function Hello<T>(arg:T):T{ return arg;}let outPut = Hello<string>('Hello Generic');let output2 = Hello('Hello Generic')console.log(outPut);console.log(outPut2);
Resources
- TypeScript Chinese Documents
- TypeScript
- TypeScript for Angular 2-part 1 (an Introduction)
Original address: http://muyunyun.cn/posts/66a54fc2/
From JavaScript to TypeScript