The purpose of the Typescript
Typescript is a solution to the problem of dynamic typing in Javascript, which is inconvenient to read and a performance penalty for browser parsing
The text start
variable
Basic types of
Common basic types include Boolean, Number, String, undefined, null, and so on
-
Boolean, Number, String
let count: number = 0.05; let numResult = count.toFixed(1); // Numeric types can use numeric type methods console.log(`numResult`, numResult); / / 0.5 let myName: string = 'sheldonWong'; let strResult = myName.slice(0.7); // String type you can use string type methods console.log(`strResult`, strResult); //sheldon let isUsed: boolean = true; let boolResult = isUsed.valueOf(); // Boolean types can use Boolean type methods console.log(`boolResult`, boolResult); //true // An optional type, which can be a number or a string let num_or_Str: string | number = 2; let num_or_Str2: string | number = 'sheldon'; Copy the code
-
Undefined, null,
let u: undefined = undefined; let n: null = null; Copy the code
-
Enum Enum type Usage scenario: Used to identify status
enum STATUS { REJECT, PENDING, RESOLVE } /* STATUS.REJECT ===0 STATUS.PENDING ===1 STATUS.RESOLVE ===2 */ enum STATUS { REJECT=-1, PENDING, RESOLVE } REJECT ===-1 // Changing a value changes the following value: status.pending ===0 status.resolve ===1 */ Copy the code
Note that:
- Naming should avoid keywords
- You can also set it value by value if necessary
The compound type
-
Object
let person1: { name: string, age: number } = { name: 'sheldon'.age: 25 }; let person2: { name: string, age: number } = { name: 'Tom'.age: 21 }; Copy the code
If a variable of the same type is needed, alias names can be used instead of duplicate objects
type Person = { name: string, age: number, }; let person1: Person = { name: 'sheldon'.age: 25 }; let person2: Person = { name: 'foo'.age: 26 }; Copy the code
-
Array
let strArray: string[] = ['s'.'h'.'e'.'l'.'d'.'o'.'n']; let numArray: number[] = [1.2.3.4.5.6.7]; let list: Array<number> = [1.2.3.4.5.6.7]; // Store objects in an Array let ObjArray3: { name: string, age: number }[] = [{ name: 'sheldon'.age: 25 }]; / / is equivalent to let ObjArray3: Person[] = [{ name: 'sheldon'.age: 25 }]; Copy the code
-
Turple (New data type for Ts)
let x: [string, number] = ['hey'.10]; // Tuples specify positions and lengths, otherwise the same as arrays // A tuple is a fixed array let y: (string | number)[] = [25.'sheldon']; // Different declarations lead to different results Copy the code