preface
Because I’m currently learning typescript; If you want to take notes while studying, you can also turn them over and share them with beginners like me. Look forward to your advice.
Introduction to the
What is a TypeScript
TypeScript is the supertype of Javascript. It can be edited to Javascript, compiled code can run on any browser, TypeScript compilation tools can run on any server and system, and it is open source.Copy the code
Why TypeScript
1. TypeScript makes code more readable and maintainable. Most errors can be found when editing is interrupted, rather than when the program is running. Enhanced editor and IDE functions, including code completion, interface prompts, etc. 2. Have an active community Most third-party libraries have TypeScript type definition filesCopy the code
Install the TypeScript
TypeScript command-line tools are installed as follows:
npm i -g typescript
The above commands will install the TSC command in a global environment, after which we can execute the TSC command on any terminal. We can simply create a file hello. TSC and we can run the command to the directory where the current file is
tsc hello.tsc
Code hello.tsc before editing
function sayHello(person: string) {
return `Hello,${person}`;
}
let user = 'Mark';
console.log(sayHello(user));
Copy the code
TSC hello. TSC will automatically generate a hello.js in the sibling directory
function sayHello(person) {
return `Hello,${person}`;
}
let user = 'Mark';
console.log(sayHello(user));
Copy the code
What happens if we pass in a non-string argument to the sayHello method
function sayHello(person: string) {
return `Hello,${person}`;
}
let user = 10010;
console.log(sayHello(user));
Copy the code
Argument of type ‘number’ is not assignable to parameter of type ‘string’. You’ll notice that TypeScript compilations generate compilation results even if errors are reported, and we can still use the compiled file.
basis
We’ve taken a quick look at TypeScript installation and a simple Hello instance. We’ll introduce common TypeScript types and some basic concepts to get a feel for TypeScript.
Primitive data type
Boolean number string NULL undefined and es6’s new type Symbol; Boolean number string null undefined is used in TypeScript
boolean
Boolean is the most basic data type. In TypeScript, Boolean is used to define Boolean values.
let isSay: boolean = false; // We are looking at the following one if we create a Boolean using the constructor ???? let createBoolean: boolean = new Boolean(8); // Type 'Boolean' is not assignable to Type 'Boolean'.Copy the code
number
Define numeric types using number:
Let age: number = 25 let age: number = 25 let age: number = 25Copy the code
string
Use string to define numeric types:
Let name: string = 'mark' let name: string = 'markCopy the code
A null value
Void in JavaScript there is no such thing as a null value, but in TypeScript we can use Void to represent functions that return no value at all:
Function sayHello(): void{console.log(' I don't have any return value '); }Copy the code
null & undefined
In TypeScript, null and undefined are used to define these two primitive data types:
let m: undefined = undefined;
let n: null = null;
Copy the code
Note: Because undefined and NULL are subtypes of all types, null undefined can be assigned to other types
let m: undefined = undefined; let age: number = m; // Edit passedCopy the code
Any value
An arbitrary value (any) is used to indicate that assignments of any type are allowed.
What is an arbitrary value type
Above we said that if it is a normal type, it is not allowed to change the type during assignment, but if it is any, it is allowed to be assigned to any type.
let age: number = 1; Number age = 'one'; // let anyAge: any = 'one'; anyAge = 1; // Edit passedCopy the code
Type inference
If no type is explicitly specified, TypeScript infers a type according to the rules of type inference. Such as:
let age = 1; age = 'one'; //TypeScript assumes that a type is equivalent to let age: number = 1 when no type is explicitly specified; age = 'one';Copy the code
The joint type
Union type?
The union type indicates that the value can be one of many types.
let age: string | number; age = 1; age = 'one'; // The above compilation passed; // If age is Boolean age = false; // Compile errorCopy the code
Through the above code can get a conclusion: the let age: string | number, the type of the age is only a string or number, is not other types.
Access the properties and methods of the union type
When TypeScript doesn’t know what type a variable of a union type is, we can only access properties or methods that are common to all types of the union type:
let age: string | number; age = 1; console.log( age.length ); Age = 'one'; console.log( age.length ); / / 3Copy the code
Type of object
In TypeScript we define the type of an object — interfaces
interface Person {
name: string;
age: number;
}
let user: Person = {
name: 'mark', age: 1,} // If welet user1: Person = {
name: 'mark',
}
// or
let user2: Person = {
name: 'mark',
age: 1,
work: 'web'} // Edit errorCopy the code
It is not allowed to define a variable with fewer attributes than the interface or with more attributes than the interface. Therefore, the shape of the variable must be the same as the interface when assigning values.
What if we could add and subtract at will without wanting to match a shape exactly? Optional attributes and optional attributes can be used in this case optional attributes: the attribute may not have any attributes: the attribute may be of any type, but note that once any attribute is defined, the type of the identified attribute and optional attribute must be a subset of its type.
insterface Person { name: string; age? : number; [propName: string]: any; }let user: Person = {
name: 'mark',
age: 1,
work: 'web'}; // If any type is defined as string, the above code will report an error. insterface Person { name: string; age? : number; [propName: string]: string; //error TS2411: Property'age' of type 'number' is not assignable to string index type 'string'
}
Copy the code
It’s common to expect that some fields can only be assigned at creation time, such as the ID in the data; How do you define read-only attributes in TypeScript?
interface Person {
readonlyid: number; name: string; age? : number; [propName: string]: any; }let user: Person = {
id: 1,
name: 'mar; ',
work: 'web'}; user.id = 2; // Error Cannot assign to'id' because it is a constant or a read-only property.
Copy the code
Array type
Array types can be represented as follows:
Type +[] notation
letOf which: number [] = [1, 2, 3, 4, 5];let ages1: number[] = [1, 2, 3, '4']; . / / an error which push ('2'); / / an errorCopy the code
Array generic Array< type >
let ages: Array<number> = [1, 2, 3];
Copy the code
Represent arrays with interfaces
interface NumberArray {
[index: number]: number;
}
let ages: NumberArray = [1, 1, 2, 3, 5];
Copy the code
Type of function
A function has input and output. To constrain it in TypeScript, both input and output are taken into account, where the type definition of a function declaration is simpler:
function sum(x: number, y: number): number {
returnx + y; } // es6 => is used to represent the function definition, the left side is the input type, need to be parenthesized, the right side is the output typelet sum: (x: number, y: number) => number = function (x: number, y: number): number {
return x + y;
};
Copy the code
It is not allowed to enter additional (or less than required) arguments as in other types:
conclusion
This is a primer on TypeScript. Is also a note of their own learning. Helpless level is limited, hope everybody big guy points out a problem, thank!