Class classes (attributes, methods)
Public c. Protected: Private: private.
class Person { public name: string; //public = public; Can be used outside of the current class, subclass, and so on; Protected gender: string = 'male '; //protected, current class, and derived subclasses can be used; Private Age: number = 27; // Assign the default value 27; Private is private and can only be used in the current Person class; constructor(name: string, /*gender: string,*/ public username: string) { this.name = name; this.username = username; /*this.gender = gender; */ } printAge(age: number) { this.age = age; console.log(this.age); this.setGender(this.gender); } /*private*/ setGender(gender: string) {// Add the private attribute "setGender" as a private attribute, which can only be accessed in class "Person". this.gender = gender; console.log(gender); }} const person = new person ('yaobinggt', /*' male ',*/ 'yaouu'); console.log(person.name, /*person.gender,*/ person.username); // Gender is protected (protected, cannot be used externally) person.printage (32); Person. SetGender (" female ")Copy the code
Class inheritance
The parent class left left left
class Person { public name: string; Protected gender: string = 'male '; private age: number = 27; Constructor (name: string,public username: string) {// Constructor = name; this.username = username; } printAge(age: number) { this.age = age; console.log(this.age); } private setGender(gender: string) {// Add the private property "setGender" as a private property, which can only be accessed in class "Person". this.gender = gender; } printName(name: string) { this.name = name; console.log(this.name); }}Copy the code
Subclasses left left left
Student extends from the (extends) Person class; A subclass extends a parent class to get all the content of the parent class, but not to use things that are private
class Student extends Person { public studentId: number; constructor(name: string, username: string, studentId: number) { super(name, username); //console.log(this.gender); / / / / male console. The log (enclosing age); // The property "age" is private and can only be accessed in the class "Person". this.studentId = studentId; / / this. SetGender (' female '); StudentPrint () {console.log(this.studentid);} studentPrint() {console.log(this.studentid);} studentPrint() {console.log(this.studentid); } printName(name: string) {// Override the parent method this.name = name; console.log(this.name); }} const yaobinggt = new Student(' yao Bing ', 'Yao UU', 20200810); //console.log(yaobinggt.name, yaobinggt.username,); // Yao Bing yao UU console.log(yaobinggt); //Student {username: "yao UU", gender:" male ", age: 27, name: "Yao Bin ", studentId: 20200810} yaobinggt. StudentPrint (); //20200810 yaobinggt.printAge(2); // Parent methods can be calledCopy the code
Set get
Used to separate private and publicable properties
const l = console.log; class Person { private _name: string = 'yaobinggt'; // Usually a private attribute is defined with an underscore; Set setName(val: string) {this._name = val; } // Private property value (get) get getName() {return this._name; Let person = new person (); l(person.getName); //yaobinggt person.setName = 'yaouu'; // assign yaouu l(person.getName); // Value: yaouuCopy the code
Static Static properties and methods
//class static attributes and methods const l = console.log; Class Person {static PI: number = 3.14; Static calcCircle(val: number): number {// static method return this.PI * val; } } l(Person.calcCircle(8)); / / 25.12Copy the code
Namespace namespace
Can be used to isolate the contamination of our environmental variables; In a large project, we can have a lot of variables, and sometimes there will be variable conflicts. Namespaces can solve the problem of variable conflicts, and namespaces can be a large TS file, part of the contents of another inside;
To make an external call, add export
const l = console.log; namespace MyMath { export const l = console.log; Export const PI: number = 3.14; export function sumValue(num1: number, num2: number): number { // return num1 + num2; } export function calcCircle(val: number) { return PI * val; }} const PI: number = 2.66; MyMath.l(MyMath.sumValue(20, 10)); //30 l(PI); / / 2.66 MyMath. L (PI); / / 2.66 MyMath. L (MyMath. PI); / / 3.14Copy the code
Namespace splitting
Take the namespace code as an example and split it into three files
calcCircle.ts
Namespace MyMath {const PI: number = 3.14; export function calcCircle(val: number) { return PI * val; }}Copy the code
sumValue.ts
namespace MyMath { export function sumValue(num1: number, num2: number): number { return num1 + num2; }}Copy the code
app.ts
const l = console.log; l(MyMath.calcCircle(8)); / / 25.12 l (MyMath sumValue (5, 15)); / / 20Copy the code
Then comes the crucial step: Open the terminal and type:
tsc –outfile app.js calcCircle.ts sumValue.ts app.ts
TSC: The command we’re going to execute –outfile: indicates the name of the file we’re going to output (so app.js). After the output file, we’re going to package those TS files as app.js
Multinamespace
Add another namespace to the calccircle. ts code and export to the external references as well
Namespace MyMath {// Multinamespace export namespace Circle {const PI: number = 3.14; export function calcCircle(val: number) { return PI * val; }}}Copy the code
App.ts how to reference:
const l = console.log; l(MyMath.Circle.calcCircle(8)); / / 25.12Copy the code
Namespace introduction
/// in the ts file to refer to
/// <reference path="calcCircle.ts" /> /// <reference path="sumValue.ts" /> const l = console.log; l(MyMath.Circle.calcCircle(8)); / / 25.12 l (MyMath sumValue (5, 15)); / / 20Copy the code
Then, once introduced, just compile app.ts
tsc app.ts –outFile app.js
Use of the module module
calcCircle.ts
Export const PI: number = 3.14; Export function calcCircle(val: number) {return PI * val; }Copy the code
app.ts
const l = console.log; Import {PI, calcCircle} from './stuff/calcCircle' l(PI);Copy the code
With app.ts, I need to compile it first
- From the command line, type TSC and compile to app.js:
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var l = console.log; var calcCircle_1 = require("./stuff/calcCircle"); l(calcCircle_1.PI); Exports is not definedCopy the code
- TSC –module commonjs app.ts and compile to app.js:
"use strict"; exports.__esModule = true; var l = console.log; var calcCircle_1 = require("./stuff/calcCircle"); l(calcCircle_1.PI); Exports is not definedCopy the code
- TSC –module AMD app.ts and compile to app.js:
define(["require", "exports", "./stuff/calcCircle"], function (require, exports, calcCircle_1) { "use strict"; exports.__esModule = true; var l = console.log; l(calcCircle_1.PI); }); Error: define is not definedCopy the code
In summary, neither CommonJS nor AMD nor any other parser can parse TS into browser-aware JS. So we need a SystemJS (version 2.0.0 or later)
index.html
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > TypeScript < / title > < script SRC = "https://cdn.bootcdn.net/ajax/libs/systemjs/0.21.5/system.js" > < / script > < / head > < body > < script > System. Config ({ BaseUrl: "/", packages: {"/": {"defaultExtension": "js"// Make your JS readable by your browser}}}) system.import ("app.js"); </script> </body> </html>Copy the code
app.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var l = console.log; Var calcCircle_1 = require("./stuff/calcCircle"); l(calcCircle_1.PI); / / 3.14 l (calcCircle (32)); / / 100.48Copy the code
App.ts we can also introduce modules in a different way
sumValue.ts
export default function sumValue(num1: number, num2: number): number {
return num1 + num2;
}
Copy the code
const l = console.log; Import {PI, calcCircle} from './stuff/calcCircle'; import * as Circl from './stuff/calcCircle'; Import sum from './stuff/sumValue'; // another method to introduce l(circl.pi); / / 3.14 l (Circl. CalcCircle (32)); / / 100.48 l (sum (10, 6)); / / 16Copy the code
Interface interface
Interface is actually a very important concept in object-oriented language, JS is not object-oriented language so there is no such a concept of interface, but TS has such a concept of interface; We can use an interface to define all of our properties, its type, which is in some sense familiar with the alias of the type
// interface Person {name: string; age: number; // Simple colon, must write sex? : string; / /? : Optional readonly salary: number; [propName: string]: any greet(): void; } type Person2 = {name: string, age: number} let person: person = {name: string, age: number} "Yaobinggt ", age: 28, sex: "box", salary: 3000, greet() {console.log("I love litter UU")}} // Call person.greet(); //I love litter UU function printPerson(person: Person) {console.log(' I am ${Person. Name}, this year ${Person. Age}, gender ${Person.Copy the code
Interface Interface inheritance
//interfacr interface PersonInterface {name: string; age: number; // Simple colon, must write sex? : string; / /? : Optional readonly salary: number; [propName: string]: any greet(): void; } // Interface extends PersonInterface {work: string; } const employee: Employee = { name: 'yaobinggt', age: 32, salary: 6000, sex: 'boy', work: Greet () {console.log('hello world')}} console.log(employee); employee.greet();Copy the code
Generics (Generic)
Use generics in functions; Let TS infer the type
function identify<T>(arg: T): T { return arg; } const l = console.log; l(identify<string>('string')); // The type can be specified explicitlyCopy the code
Using generics in interfaces: You can specify types explicitly; You can also hand it over to TS to infer the type.
const l = console.log; interface GenericIdentify { <T>(age: T): T; } function identify<T>(arg: T): T { return arg; } let myIdentify: GenericIdentify = identify; MyIdentify <string>("yao-string")); //yao-string // give ts to infer type L (myIdentify(30)); / / 30Copy the code
Generics can also be promoted in interfaces; It’s not defined in the function; It’s defined on the interface.
const l = console.log; interface GenericIdentify<T> { (age: T): T; } function identify<T>(arg: T): T { return arg; } let myIdentify: GenericIdentify<number | string> = identify; MyIdentify ("yao-string")); myIdentify("yao-string"); //yao-string // give ts to infer type L (myIdentify(30)); / / 30Copy the code
Add constraints for generics
const l = console.log; Function getLength<T extends {length: any}>(obj: T): any {function getLength<T extends {length: any}>(obj: T): any { } const obj = { name: 'yaobinggt', age: 28, length: 12 } l(getLength(obj)); / / 12Copy the code
const l = console.log; Function getLength<T extends Number >(obj: T): any {function getLength<T extends Number >(obj: T): any { } const obj = 28; GetLength (obj)); getLength(obj); / / 28Copy the code
The use of Generic classes
Ordinary class
const l = console.log; class CountNumber { number1: any; number2: any; constructor(num1: number, num2: number) { this.number1 = num1; this.number2 = num2; } calcalate(): number { return this.number1 + this.number2; } } const constNumber = new CountNumber(10, 12) l(constNumber.calcalate()); / / 22Copy the code
Add generic classes
const l = console.log; class CountNumber<T> { number1: T; number2: T; constructor(num1: T, num2: T) { this.number1 = num1; this.number2 = num2; } calcalate(): number { return +this.number1 + +this.number2; } } const constNumber = new CountNumber<string>("10", "12") l(constNumber.calcalate()); / / 120Copy the code
You can also place a constraint on generics
const l = console.log; Class CountNumber<T extends Number > {// Restrict generics to number number1: T; number2: T; constructor(num1: T, num2: T) { this.number1 = num1; this.number2 = num2; } calcalate(): number { return +this.number1 + +this.number2; }} const constNumber = new CountNumber<number>(10, 12)// Count l(constNumber.calcalate()); / / 22Copy the code