Ts introduction
Typescript is a programming language developed by Microsoft. It is a superset of javascript that follows the latest ES6 scripting language specification. Typescript extends the syntax of javascript. Any existing javascipt program can run in the typescript environment unchanged
Typescript simply adds new es6-compliant syntax and class-based object-oriented programming features to javascript.
Ts installation and compilation
Typescript Chinese website: www.tslang.cn/docs/home.h…
NPM install -g typescript
Compilation: TSC xxx.ts When compiled this way, a JS file is generated
// greeter.ts
function greeter(person) {
return "Hello, " + person;
}
let user = "Jane User";
document.body.innerHTML = greeter(user);
Copy the code
Then running TSC greeter.ts produces a JS file greeter.js
// greeter.ts function greeter(person: string) { return "Hello, " + person; } let user = "Jane User"; document.body.innerHTML = greeter(user); In fact, there is no difference between the two files at first glance, because we use js syntax in TS file, there is no type annotationCopy the code
If this approach is too cumbersome (running the js file every time to see the result), we can use the TS-Node package to simplify the compilation of TS files
Install ts-node: NPM install -g TS-node
Ts can be compiled by using ts-node greeter.ts on the terminal or command line. Js files are not regenerated
Here we put the ts-Node address: www.npmjs.com/package/ts-…
Underlying data types
To make a program valuable, we need to be able to handle the simplest units of data: numbers, strings, structures, booleans, and so on. TypeScript supports almost the same data types as JavaScript, and it also provides useful enumerated types for us to use.
Primitive data types include: Boolean, numeric, string, NULL, undefined, and the new types Symbol and BigInt in ES6.
Here we focus on the first five raw data types used in TypeScript
//boolean let isDone: boolean = false; let hasDone: boolean = true; // let decLiteral: number = 6; let hexLiteral: number = 0xf00d; let binaryLiteral: number = 0b1010; let octalLiteral: number = 0o744; // string let name: string = "bob"; name = "smith"; let name: string = `Gene`; let age: number = 37; let sentence: string = `Hello, my name is ${ name }. I'll be ${ age + 1 } years old next month.`; //Null and Undefined // By default Null and Undefined are subtypes of all types. Let u: undefined = undefined; let n: null = null; Let a: number = null | undefined / / null / / JavaScript not null (Void) concept, in the TypeScript, can use Void said there is no return value of function: function alertName(): void { alert('My name is Tom'); }Copy the code
Summary of object types and their residual types
Let list: number[] = [1, 2, 3]; let list: number[] = [1, 2, 3] let list: (number| string)[] = [1, 2, 3,'str']; // The second way is to use Array generics, Array< element type > : let list: Array<number> = [1, 2, 3]; The Tuple type allows you to represent an array with a known number and type of elements. The elements need not be of the same type. For example, you can define a pair of tuples of type string and number. // Declare a tuple type let x: [string, number]= ['hello', 10]; // Initialize it x = ['hello', 10]; // OK // Initialize it incorrectly x = [10, 'hello']; // Error // When adding an out-of-bounds element, its type is limited to the combined type of each type in the tuple: let Tom: [string, number]; tom = ['Tom', 25]; Tom.push ('male'); //[ 'Tom', 25, 'male' ] tom.push(true); //Error: Argument of type 'true' is not assignable to the parameter of type 'string | number'. / / the enumeration: enum type is a complement of JavaScript standard data type. Enum Color {Red, Green, Blue} let c: Color = color.green; //1 Default starting from index 0 enum Color {Red = 1, Green, Blue} let C: Color = color.green; Enum Color {Red = 1, Green, Blue} let colorName: string = Color[2]; console.log(colorName); //Green shows 'Green' because it has a value of 2 // any in the code above. 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. If it is a normal type, it is not allowed to change the type during assignment, but let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; You might think that Object has a similar function, just as it does in other languages. But a variable of type Object only allows you to assign arbitrary values to it - but you can't call arbitrary methods on it, even if it does have them: accessing any property on any value is allowed, whereas Object does not. notSure.ifItExists(); // okay, ifItExists might exist at runtime notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) let prettySure: Object = 4; prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'. The any type is also useful when you only know 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; // Const teacher: {name: string, age: number} = {name: 'dell', age: 18}; console.log('obj:', teacher); Const getTotal: () => number = () => {return 123; }; const getTotal = (person:Person):string =>{ return person.a; }; Const getTotal(a:number,b:number):number {return a+b; }; GetTotal (10,20) // void function returns no value const sayHello():void{console.log('hello')}; / / function parameters of the deconstruction of writing function add (first, second, attach {first: number, second: number}) : number + second} {return first const total = add({first:10,second:20})Copy the code