preface
I have read the document systematically in these two days and recorded the basic definition and usage. Some definitions in the document will not be introduced, but only the understanding and usage of basic concepts.
First put the look of these documents: Runoob | TypeScript | xcatliu
Introduction to the
TypeScript:
Typed JavaScript at Any Scale. JavaScript with a type system added for projects of any size.
TypeScript’s core design philosophy:
The introduction of a static type system improves the maintainability of code and reduces possible bugs while preserving JavaScript runtime behavior in its entirety.
For more on TypeScript, see this chapter from xCATLiu: What is TypeScript
A brief summary of personal understanding:
Because JavaScript is an interpreted language, there is no compile phase and type checking is done at run time, often resulting in runtime errors. TypeScript, on the other hand, compiles to JavaScript before running, and performs type checking at compile time, largely compensating for JavaScript’s shortcomings.
TypeScript only statically checks types at compile time, and if errors are found, an error is reported at compile time. At run time, like normal JavaScript files, there is no type checking.
Quote summary:
- TypeScript is JavaScript with a type system added for projects of any size.
- TypeScript is a statically typed, weakly typed language.
- TypeScript is fully javascript-compatible and does not modify JavaScript runtime features.
- TypeScript can be compiled to JavaScript and run in a browser, Node.js, or any other environment that can run JavaScript.
- TypeScript has many compilation options, and it’s up to you to be as strict as you want with type checking.
- TypeScript can coexist with JavaScript, which means that JavaScript projects can migrate to TypeScript gradually.
- TypeScript enhances the editor (IDE) by providing code completion, interface hints, jump to definitions, code refactoring, and more.
- TypeScript has an active community, and most common third-party libraries provide type declarations.
- TypeScript keeps pace with the standards, conforming to the latest ECMAScript standard (Stage 3).
TypeScript command-line tools are installed as follows:
npm install -g typescript
Copy the code
The above commands will install the TSC command in the global environment, and after the installation is complete, we can execute the TSC command anywhere.
Compiling a TypeScript file is simple:
tsc hello.ts
Copy the code
We have a convention that files written in TypeScript end with.ts and React end with.tsx.
Basic concept
The base type
The TypeScript base type for the rookie tutorial column is clear. See the official documentation for more details.
- Any type any – A variable declared as any can be assigned a value of any type.
- Number type number – a double – precision 64 – bit floating-point value. It can be used to represent integers and fractions.
- String type String – A series of characters that use single or double quotation marks to indicate the string type.
- Boolean type Boolean – Represents logical values: true and false.
- Array type – Declares variables as arrays.
- Tuple – An array representing the number and type of known elements. The elements need not be of the same type.
- Enumeration – Enumeration types are used to define sets of values.
- Void – Identifies the type of value returned by the method, indicating that the method has no return value.
- Null – Indicates that the object value is missing.
- Undefined – Used to initialize a variable to an undefined value.
- Never – never is a subtype of other types, including null and undefined, and represents a value that never occurs.
Type inference
Type inference: TypeScript extrapolates a type when no type is explicitly specified.
let num = 'seven' // let num: string = 'seven'
num = 7; / / error
Copy the code
If there is no assignment at the time of the definition, it will be inferred whether there is an assignment or notany
Type without being type checked at all.
let num; // equivalent to let num: any; Unassigned values are inferred to be of type any when defined
num = 'seven'; / / right
num = 7; / / right
Copy the code
The joint type
The union type indicates that the value can be one of many types. Using | separated for each type.
let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven'; / / right
myFavoriteNumber = 7; / / right
myFavoriteNumber = true; / / error
// Use the union type as a function argument:
function disp(name:string|string[]){... }// We can also declare arrays as associative types:
var arr:number[] |string[];
Copy the code
interface
An interface is a set of abstract method declarations. It is a collection of method characteristics. It is an abstraction of behavior that needs to be implemented by classes.
// Define an interface Person
interface Person {
readonly id: number; // Read-only attribute
firstName: string; lastName? :string; / /? The question mark represents an optional attribute
sayHi:() = > string;
[propName: string] :any; // Arbitrary attribute - Once an arbitrary attribute is defined, the type of both the determined attribute and the optional attribute must be a subset of its type
// commandline:string[] | string | (()=>string); // Union type
}
// When assigning values, the shape of the variable must be the same as the shape of the interface.
let tom: Person = {
id: 888.// initialize - Read-only attributes are no longer allowed to be assigned after initialization
firstName: 'Tom'.sayHi: (a) :string= >{return "Hi"}}// Interface inheritance Use commas (,) to separate inherited interfaces.
// Single interface inheritance syntax format:
//Child_interface_name extends super_interface_name
// Multiple interface inheritance syntax format:
/ / Child_interface_name extends super_interface1_name, super_interface2_name,... ,super_interfaceN_name
Copy the code
Array type
In TypeScript, array types are defined in a variety of flexible ways.
// Define an array of type number. The array can only contain type number
let num: number[] = [1.2.3.4];
// Define a string array that can only contain strings
let strArr: string[] = ['a'.'b'.'c']
// The Array generic Array
can also be used to represent arrays:
let arr: Array<number> = [1.2.3]
// Define an array of any type
let list: any[] = ['xcatliu'.25, { website: 'http://xcatliu.com' }];
// Use interfaces to represent arrays - often used to represent arrays of classes
interface NumberArray {
[index: number] :string; // Set the index of the array to number and the element value to string
}
let fibonacci: NumberArray = ['a'.'b'.'c'];
Copy the code
Type of function
Detailed documentation
The function needs to take into account both input and output:
// Arguments x and y must be passed as number. More or less arguments are not allowed
// The return value of the function is also defined to be of type number
function sum(x: number, y: number) :number {
return x + y;
}
Copy the code
Types of assertions
Type assertions can be used to manually specify the type of a value, that is, to allow variables to change from one type to another.
Type assertions have two equivalent forms:
- Value as type
- < type > value
In the TSX syntax (ts version of the React JSX syntax) the value must be of type AS.
Type inference is the autonomous behavior of TS, and type assertion is the manual behavior that we change the type ourselves. Do not abuse type assertions, which can lead to runtime errors.
tuples
Different types of elements are allowed to be stored in tuples, which can be passed to functions as arguments.
var tuple_name = [value1,value2,value3,...value n]
// Declare a tuple and initialize it:
var mytuple = [10."Runoob"];
// Access the tuple
mytuple[0]; / / 10
// push() adds the element to the end of the tuple
mytuple.push(12) // [10,"Runoob",12]
// pop() removes the last element from the tuple and returns the removed element
mytuple.pop() / / 12
// Update the tuple
mytuple[0] = 121; // [121,"Runoob"]
// Deconstruct tuples
var [x,y] = mytuple; // x => 121 y => "Runoob"
Copy the code
The enumeration
The enumeration (Enum) type applies to scenarios where the value is limited within a certain range, for example, there are only seven days in a week, and the color is limited to red, green and blue.
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"= = =0); // true
console.log(Days["Mon"= = =1); // true
console.log(Days["Tue"= = =2); // true
console.log(Days["Sat"= = =6); // true
console.log(Days[0= = ="Sun"); // true
console.log(Days[1= = ="Mon"); // true
console.log(Days[2= = ="Tue"); // true
console.log(Days[6= = ="Sat"); // tru
Copy the code
The generic
Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use.
function createArray<T> (length: number, value: T) :Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray<string> (3.'x'); // ['x', 'x', 'x']
Copy the code
Declaration file
// Declaration files with a.d.ts suffix, for example:
runoob.d.ts
// Declare file or module syntax format is as follows:
declare module Module_Name {}
// TypeScript introduces declaration file syntax formats:
<reference path="runoob.d.ts" />
Copy the code
conclusion
emmm.. Feels like a copy of the document ah!! Ak47 schematic item and loot added!! Added: ak47 schematic item and loot added
Basic types, union types, type inferences, type assertions, interfaces, tuples, enumerations, classes, generics, aliases, namespaces, declaration files, etc. These concepts are much clearer after reading. Another day of hard work, I am great.
end.