A, install,
Install typescript globally (you already have Node installed by default)
npm install -g typescript
Copy the code
Once installed, you are ready to develop using typescript
// demo.ts
function demo01()
{
let test: string = 'a test typescript';
console.log(test)
}
demo01()
Copy the code
Typescript-ending. Ts files cannot be run directly; they need to be compiled to a.js file to run
Compilation mode:
Ts file NPM install -g ts-node ts-node demo.ts file NPM install -g ts-node ts-node demo Run the TS file directlyCopy the code
Static type
// demo2.ts
const count : number = 1;
Copy the code
Here we define the count variable, where: number defines a static type.
Note ⚠️ : The type of a static variable cannot be changed, but its value can.
Custom static types
. interface Demo { name: string; age: number; } let demo : Demo = { name: '23', age: 23 } console.log(demo); .Copy the code
Data types
Basic data types: number, string, Boolean, NULL, undefined, symbol
Object types: object, array, class, function
Number
All numbers in TypeScript are floating point numbers. These floating point numbers are of type number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.
let num : number = 11111;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
Copy the code
String
Let STR: string = 'This is the base static type of string '; Let str1: string = "This is the base data type ";Copy the code
Boolean
let bool : boolean = true;
Copy the code
Null
let nul : null = null;
Copy the code
Undefined
let unde : undefined = undefined;
Copy the code
Symbol
let sym : symbol = Symbol('foo');
let sym1 : symbol = Symbol(123);
Copy the code
object
let obj : {
user: string,
age: number,
sex: boolean
} = {
user: 'xiaoming',
age: 26,
sex: true
}
console.log(obj) // { user: 'xiaoming', age: 26, sex: true }
Copy the code
An array of
TypeScript manipulates array elements just like JavaScript. There are two ways to define an array. First, an element type can be followed by [] to represent an array of elements of that type
// Let arr: Object[] = [null, undefined, 0, '123', true]; let arr1 : String[] = ['null', 'undefined', '0', '123', "true"]; console.log(arr) // [ null, undefined, 0, '123', true ] console.log(arr1) // [ 'null', 'undefined', '0', '123', // Array< element type > const arr3: Array<string> = [' STR ', 'STRR ',' STRRR '];Copy the code
function
Let func: () => string = () => 'small' // es6 arrow Function console.log(func) // [Function: func]Copy the code
class
class Person {} let per : Person = new Date(); // New Date() const per1: Person = new Person(); Console. log(per) // 2020-09-16T11:23:19.698z console.log(per1) // Person {}Copy the code
Enum enumeration
// dmeo.ts enum Color {Red, Green, Blue} let c: Color = Color.Green let r: Color = Color.Red let b: Color = Color.Blue // demo.js var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; })(Color || (Color = {})); var c = Color.Green; var r = Color.Red; var b = Color.Blue; console.log(c, b, r); console.log(Color) // { '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2} console.log(c, b, r) // 1 2 0 r is 0, because the default is to start from 0 This is enumerated / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / modify the starting order enum Colors {Pink = 1, Yellow, Purple} let p: Colors = Colors.Pink let y: Colors = Colors.Yellow let p1: Colors = Colors.Purple console.log(p,y,p1) // 1 2 3 console.log(Colors) /*{ '1': 'Pink', '2': 'Yellow', '3': 'Purple', Pink: 1, Yellow: 2, Purple: 3} (function (Colors) { Colors[Colors["Pink"] = 1] = "Pink"; Colors[Colors["Yellow"] = 2] = "Yellow"; Colors[Colors["Purple"] = 3] = "Purple"; })(Colors || (Colors = {})); var p = Colors.Pink; var y = Colors.Yellow; var p1 = Colors.Purple; console.log(p, y, p1); // 1 2 3 console.log(Colors); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / modify each value enum Job {= 1 Fe = 12, Php, Java = 4} let f: Job = Job. Fe; let p3: Job = Job.Php; let j: Job = Job.Java; let fe: string = Job[12]; let php: string = Job[1]; let java: string = Job[4]; console.log(f,p3,j,fe,php,java) // 12 1 4 Fe Php Java console.log(Job) // { '1': 'Php', '4': 'Java', '12': 'Fe', Fe: Php: 1, Java: 4} /* */ / (function (Job) { Job[Job["Fe"] = 12] = "Fe"; Job[Job["Php"] = 1] = "Php"; Job[Job["Java"] = 4] = "Java"; })(Job || (Job = {})); var f = Job.Fe; var p3 = Job.Php; var j = Job.Java; var fe = Job[12]; var php = Job[1]; var java = Job[4]; console.log(f, p3, j, fe, php, java); // 12 1 4 Fe Php JavaCopy the code
The above is enumeration example, similarly, I can understand the following for JS is enumeration 🤔️?
{
4: 'java',
34: 'php',
2: 'js'
}
Copy the code
Any
Sometimes we want to specify a type for variables whose type is not known at programming time. These values may come from dynamic content, such as user input or third-party code libraries. In this case, we don’t want the type checker to check these values and just pass them through compile-time checks. Then we can mark these variables with type any
let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; 😂) let notSure: any = 4; notSure.ifItExists(); // okay, ifItExists might exist at runtime notSure.toFixed(); let prettySure: Object = 4; prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'. // The any type is also useful when you know only part of the data type. For example, you have an array that contains different types of data let list: any[] = [1, true, "free"]; list[1] = 100;Copy the code
Nerver
The never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all; Variables can also be of type never, when they are bound by type protection that is never true.
The never type is a subtype of any type and can be assigned to any type; However,
A type is a subtype of never or can be assigned to type never (in addition to never itself). Even any cannot be assigned to never.
Here are some functions that return type never:
Function error(message: string): never {throw new error(message); } // The inferred return value type is never function fail() {return error("Something failed"); Function infiniteLoop(): never {while (true) {}}Copy the code
Object
Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.
Use the object type to better represent apis like Object.create. Such as:
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
Copy the code
Types of assertions
// let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; // let someValue: any = "this is a string"; let strLength: number = (someValue as string).length;Copy the code
Note ⚠️ : When you use JSX in TypeScript, only AS syntax assertions are allowed
Type annotation and type inference
Type annotation
This is called a type annotation
let count : number = 23;
Copy the code
Type inference
Type inference does not write the required type of data, but the system field is inferred to be of type number. Here, no type comment is written, but TS still recognizes that count1 is of type number, which is called type inference.
let count1 = 24;
Copy the code
Write or not write type comments, according to the business itself to determine, for example, calculate the sum of two numbers, if you do not write comments into the string is a splicing, so flexible according to the business itself to determine whether to write type comments.
// This is the calculation function, which needs to be written, otherwise it is the string concatenation function. function sumTwo(one : number, two : number) { return one + two; } the console. The log (sumTwo (2, 3)); // 5 // console.log(sumTwo('2','3')); / / an errorCopy the code
Function parameters and return type definitions
parameter
Underlying data types
Function echo(STR: string) {console.log(STR)} function echo1(bool: bool) Boolean) {console.log(' Printed value is: '+ (bool? 'true' : 'false ')); } echo('he is a huamen'); // he is a huamen echo1(true); // Prints true echo1(false); // The printed value is: falseCopy the code
Object type
Function echo2(str3: Object []) {console.log(str3)} function echo3({one, two} : {one: string, two: {one: string, two: Function echo4(STR: () => "33") {STR ()} function echo5(time: Date) { console.log(time.getTime()) } echo2([null, undefined, 0, true]); // [ null, undefined, 0, true ] echo3({one: '3', two: '55'}); // 355 echo4(function () { return '33'; }); // undefined echo5(new Date()); / / 1600256196949Copy the code
The return value
There is no return value
The function returns no value. Add the type annotation void to the function
Function echo6() : void {console.log(' this function returns no value ') // return 3333; Type 'number' is not assignable to Type 'void'.} echo6();Copy the code
Basic Basic data type
function echo7(num : number) : boolean
{
return num > 0;
}
console.log(echo7(9)); // true
console.log(echo7(-23)); // false
Copy the code
Object type
Function echo8() : string[] {return ['1', '2', 'STR ', 'num']; return ['1', '2',' STR ', 'num']; } console.log(echo8()) // [ '1', '2', 'str', 'num' ]Copy the code
Array types
A simple type
let arr : string[] = ['1','3', 'erder', 'sfesrfre'];
console.log(arr) // [ '1', '3', 'erder', 'sfesrfre' ]
Copy the code
Most apis return arrays or objects, so how to define object types is important!!
// If you want to use the same array, you will need to write the same type again. // The types here: type aliases, interfaces, classes are all manageable! let arr1 : {user: string, age: number}[] = [ {user: 'x', age: 23}, {user: 'y', age: 24}, ]; console.log(arr1) // [ { user: 'x', age: 23 }, { user: 'y', age: 24 } ]Copy the code
Arrays contain multiple types
Const xiaojiejie1: (string | number) [] = [' dajiao, 28, 'the teacher'] / / not a tuple, cannot locate to the type of each element, changing the order not an error.Copy the code
Type the alias
Start with the keyword type
// Type alias type male = {name: string, age: number} age: Number; } // class Demo {name: string age: number}; let arr2 : male[] = [ {name: 'aaa', sex: true}, {name: 'bbb', sex: true}, {name: 'ccc', sex: !!'true'} ] console.log(arr2) let arr3 : female[] = [ {user: 'abbb', age: 23}, {user: 'accc', age: 24}, {user: 'addd', age: 26} ] console.log(arr3) let arr4 : Demo[] = [ {name: 'xiaoming', age: 23}, {name: 'xiaoshi', age: 23}, {name: 'xiaohong', age: 23}, {name: 'xiaoguang', age: 23} ] console.log(arr4)Copy the code
Seven, yuan group
Const xiaojiejie: [string,string,number] = ['dajiao','teacher',28] // This is a tuple that defines the type of each field. If the order changes, an error is reported. // This is a tuple of a multidimensional array const xiao3: [string, string, number][] = [ ['x', 'te', 3], ['x', 'te', 3], ['x', 'te', 3], ['x', 'te', 3], ] console.log(xiao3) //Copy the code
8, Interface
define
Const findXiao = (name: string, age: number, must: Number) => {age < 24&& must > 90&& console.log(' enroll ') age > 24&& must < 90&& console.log(' eliminate ')} const xiao = {name: Const xiao1 = {name: 'laoxie ', age: 89, must: 09} //Copy the code
Same problem, write words every time, the person wants tired dead 😢
Interface interface Gril {name: string; age: number; must: number; } const xiao = {name: 'Lao Xie ', age: 21, must: 99} const xiao1 = {name:' Lao Xie ', age: 89, must: 09} const findXiao1 = (gril: Gril) => {gril.age < 30 && gril.must > 90 && console.log(" 提 升 ") } findXiao1(xiao) //Copy the code
Interface and type alias differences
Type aliases can be given directly to types, such as type Gril = string;
Interfaces must be objects
Interface is not mandatory
interface Gril1 { name: string; age: number; must: number; leg ? : string; } const findXiao2 = (gril: Gril1) => {gril.age < 30 && gril.must > 90 && console.log(" 提 升 ") Gril.leg && console.log(' I see your console.log ') const xiao2 = {name: 'old ', age: 89, must: 09, leg: {name:' old ', age: 89, must: 09, leg: "Haha "} findXiao2(xiao2) // I see your legsCopy the code
Interface adds arbitrary parameters and methods
interface Gril2 { name: string; age: number; must: number; leg ? : string; // Interface non-mandatory definition [propName :string] : any; // Allow arbitrary values, not strictly say(): string; // add a say method that returns string}Copy the code
Class Inheritance Interface (implements)
class Xiao3 implements Gril2 {
name = 'zhy'
age = 23
must = 99
say() {
return this.name
}
}
console.log(new Xiao3()) // Xiao3 { name: 'zhy', age: 23, must: 99 }
Copy the code
Interface Inheritance Interface (extends)
interface Xiao4 extends Gril2{
}
Copy the code
Nine, class,
define
class Lady {
content = 'say hi'
say() {
return this.content
}
}
const xiaohong = new Lady();
console.log(xiaohong.say()) // say hi
Copy the code
Inheritance and method rewriting
The super keyword supports methods that use the parent class, but not properties
Class Zhang extends Lady {say() {return 'here is Zhang '; } walk() {console.log(' 11111111super', super.say()) // console.log(' 11111111super', super.content) // error, Return 'while walking firecrackers '; } } const xiaozhang = new Zhang(); Console.log (xiaozhang.content) // say hi console.log(xiaozhang.say()) // Here is Zhang's rewrite of console.log(xiaozhang.walk()) // 1111111111super say hiCopy the code
Super uses the methods of the parent class
Access restrictors public,protected,private
Public: The class is accessible both internally and externally
Protected: The interior and subclasses of the class are accessible
Private: Can be accessed only within its own class
class Person { public name : string public say() { return this.name } } const zhy = new Person(); zhy.name = 'haiyang'; console.log(zhy.say()) // haiyang class Person1 { protected name : string = 'yangyang' public say() { return this.name } } const zhy1 = new Person1(); // zhy1.name = 'haiyang'; / / an error, Property 'name' is protected and only accessible within class 'Person1' and its subclasses. console.log(zhy1.say()) // yangyang class Person2 extends Person1 { public walk() { return this.name } } const zhy2 = new Person2() console.log(zhy2.walk()) // yangyang class Person3 { private name : string = 'haihai' public say() { return this.name } } const zhy3 = new Person3(); // zhy3.name = 'haiyang'; / / an error, Property 'name' is private and only accessible within class 'Person3 console.log(zhy3.say()) // haihai class Person4 Extends Person3{walk() {// return this.name, 09_cals.ts :78:17 - error TS2341: Property 'name' is private and only accessible within class 'Person3'. } } const zhy4 = new Person4() console.log(zhy4.walk()) // undefinedCopy the code
The constructor
Class Now{} class Chl extends Now{constructor() {super(); Constructors for derived classes must contain a 'super' call. console.log(1111) } } const c = new Chl();Copy the code
Getters, setters, static usage
1. Getters and setters are properties and only formal functions
2. Attribute names can be arbitrary, as long as you know what they mean
Class Xie {constructor(private num_age: number) {} class Xie {constructor(private num_age: number) {} number) { this.num_age = age } get age() { return this.num_age } } const xiaoxie = new Xie(32) console.log(xiaoxie.age) //32 is an attribute!! Xiaoxie. name = 4444 // Note the attribute!! Console. log(xiaoxie.age) // 4444 changed the age /* 1\. Static properties and methods should simply not instantiate classes, */ class StaticClass {name = 'zhy' static age = 23 say() {console.log(' I am not static ')} static walk() {class StaticClass {name = 'zhy' static age = 23 say() {console.log(' I am not static ')} static walk() { Console. log(' I am static and can use methods externally ')}} console.log(staticclass.name) // StaticClass should be an inherent property, Console. log(staticclass.age) // 23 // console.log(staticclass.say ()) // Inaccessible, Console. log(staticclass.walk ()) // I am static and can be used externallyCopy the code
Read-only properties and abstract classes
Read-only property
The keyword readonly
class Person10 { public readonly _name :string; constructor(name:string) { this._name = name; }} const person10 = new person10 ('demo') // person10. Cannot assign to '_name' because it is a read-only property. console.log(person10._name) // demoCopy the code
An abstract class
1. The keyword abstract defines the class
2. An abstract method cannot have a method body
3. Subclasses must implement abstract methods
4. An abstract class can have properties and methods from other normal classes.
Class Waiter extends Girl{skill(){console.log(){class Waiter extends Girl{skill(){console.log(){class Waiter extends Girl{skill(){console.log(){class Waiter extends Girl{skill(){console.log(){class Waiter extends Girl{skill(){console.log(){class Waiter extends Girl{skill(){console.log(){skill()} ')}} class BaseTeacher extends Girl{skill(){console.log ')}} class seniorTeacher extends Girl{skill(){console.log ') } } abstract class Girl{ name = 'zhy' say() { return 333; // Because there is no specific method, we do not write parentheses here}Copy the code