This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging
What is a type system
The type system consists of two important components:
- Type annotation (definition, annotation) – typing
- Type checking – type-checking
Type annotation
Type annotation is in the code to data (variables, functions, parameters and return values)) add types shows that when a variable or function (parameters) was noted after cannot store or incoming with annotation type does not conform to the type of annotation, TypeScript compiler can legal inspection shall be carried out in accordance with the annotation of the data type. With annotations, various editors, ides, and so on can make intelligent hints
In TypeScript, the basic syntax for type annotations is:
Let num:number = 100;Copy the code
Type test
As the name suggests, the type of data is tested. Notice here, the key word is type. Type system to detect types, not specific values (although, sometimes also can readings), such as the scope of a parameter (1-100), we can’t depend on the type system to complete the test, it should be our business logic, type system test is whether its value type for the digital!
Basic simple type annotations
- The base type
- Empty and undefined types
- Object type
- An array type
- A tuple type
- Enumerated type
- There is no value type
- Never type
- Any type
- Unknown type (Version3.0 Added)
The base type
The basic types include: string, number, Boolean
Let title: string = 'TypeScript type system First '; let num: number = 100; let isOk: boolean = true;Copy the code
Empty and undefined types
Since Null and Undefined have one and only one value, labeling a variable as Null and Undefined means that the variable cannot be modified
let a: null; a = null; // ok a = 1; // errorCopy the code
By default null and undefined are subtypes of all types. That means you can use null and undefined for other types of variables
let a: number; a = null; // okCopy the code
If a variable is declared but not assigned, the value of the variable is undefined, but if it is also untyped, the default type is any, which is specified later
// The value of 'undefined' is' number '; The type is' any 'and the value is' undefined'Copy the code
Tip 1: specify strictNullChecks configuration to true, can effectively detect null or undefined, avoid many common problems, but also can make our program more rigorous
Tip 2: The method that gets the element may return a type that contains NULL, so it’s best to make the necessary checks before you do anything
Object type
Built-in object type
In JavaScript, there are many built-in objects, such as Object, Array, Date… , we can use the object’s constructor or class to annotate
let a: object = {}; Let arr: Array<number> = [1,2,3]; Let d1: Date = new Date();Copy the code
Custom object types
On the other hand, many times, we may need a custom structured object. At this point, we can:
- Literal notation
- interface
- Define a class or constructor
Literal notation:
let a: {username: string; Age: number} = {username: 'name ', age: 35}; // ok a.username; a.age; // error a.gender; Advantages: Convenient direct disadvantages: not good for maintenance and reuseCopy the code
Interface:
Interface Person {username: string; // Person {username: string; age: number; }; Let a: Person = {username: 'username ', age: 35}; // ok a.username; a.age; // error a.gender; Advantages: High reusability Disadvantages: The interface can only be used as a type annotation, not as a concrete value. It is only an abstract structure definition, not an entity, and has no concrete function implementationCopy the code
Constructor:
class Person { constructor(public username: string, public age: number) { } } // ok a.username; a.age; // error a.gender; Advantages: relatively powerful, define the entity at the same time to define the corresponding type disadvantages: complex, such as only want to constrain the structure of the parameters received by a function, there is no need to specify a class, using the interface is easierCopy the code
extension
Wrapped objects: Wrapped objects are strings, numbers, and Boolean in JavaScript. We know that String is not the same type as String, and the same is true in TypeScript
let a: string; a = '1'; A = new String('1'); a = new String('1'); let b: String; b = new String('2'); B = '2';Copy the code
An array type
Arrays must be of the same type in TypeScript, so when you annotate the array type, you also annotate the data type stored in the array
Generic label
Arr1: Array<number> = []; arr1: Array<number> = []; // ok arr1.push(100); // error arr1.push('Toney');Copy the code
Simple annotation
let arr2: string[] = [];
// ok
arr2.push('Toney');
// error
arr2.push(1);
Copy the code
Tuple type
Tuples are like arrays, but they don’t have to store the same type of elements, but note:
- The number of initialization data and the corresponding location annotation type must be consistent –
- The out-of-bounds data must be one of the types in the tuple annotation (out-of-bounds data can be annotated without corresponding ordinal-union types
let data1: [string, number] = ['Kobe Bryant', 100];
// ok
data1.push(100);
data1.push('YaoMing');
// error
data1.push(true);
Copy the code
Enumerated type
The purpose of an enumeration is to organize the collection of a set of associated data. By using an enumeration, we can give a set of related data friendly names
enum HTTP_CODE {
OK = 200,
NOT_FOUND = 404,
METHOD_NOT_ALLOWED
};
// 200
HTTP_CODE.OK;
// 405
HTTP_CODE.METHOD_NOT_ALLOWED;
// error
HTTP_CODE.OK = 1;
Copy the code
Notes:
- Key cannot be a number
- Value can be a number, called a numeric type enumeration, or a string, called a string type enumeration, but cannot be any other value. The default value is the number: 0
- Enumeration values can be omitted, if omitted, then:
- The first enumeration value defaults to 0
- Non-first enumeration value is the previous numeric enumeration value + 1
- The enumeration value is read-only (constant) and cannot be modified after initialization
Enumeration of string types
Value of an enumeration type, or a string type
Enum URLS {USER_REGISETER = '/user/register', USER_LOGIN = '/user/login', // if the previous enumeration is a string, then the following enumeration must be manually set INDEX = 0}Copy the code
Notes:
- If the previous enumeration value is of type string, subsequent enumerations must be manually assigned
Tip: Enumeration names can be either uppercase or lowercase. It is recommended to use all uppercase names (it is usually used to mark values as constants).
There is no value type
Represents a type that has no data. It is usually used to annotate the return value type of a function that has no return value. The default annotation type is void
Function fn():void {// return undefined}Copy the code
- If strictNullChecks is false, both undefined and null can be assigned to void
- But if strictNullChecks is true, only undefined can be assigned to void
Never type
When a function never executes a return, it returns never. Unlike void, which executes a return but has no value, never does not execute a return. For example, an error is thrown, causing the function to terminate
function fn(): never {
throw new Error('error');
}
Copy the code
Any type
Sometimes we are not sure what type the value is or we can label the value as any without type checking
let a: any;
Copy the code
- If a variable is declared with no value and no type, the default is any
- Values of any type can be assigned to type any
- The any type can also be assigned to any type
- The any type has arbitrary properties and methods
Note: Marking the value as any also means that type detection for the value is abandoned, along with the IDE’s intelligent hints
Tip: When specifying noImplicitAny is set to true, an error is reported when a function argument has an implied any type
Unknown type
Unknow, new in version 3.0, is a secure version of any, but is different from any:
- Unknow can only be assigned to unknow and any
- Unknown does not have any properties or methods
Function types
Functions are important in JavaScript, but they are also important in TypeScript. Similarly, functions have their own type annotation format
- parameter
- The return value
Function name (argument 1: type, argument 2: type...) : Return value type; function add(x: number, y: number): number { return x + y; }Copy the code
conclusion
I just started to learn TypeScript. I just review some TypeScript articles in my spare time, and make notes to deepen my impression. I also hope to help students who are new to TypeScript like me, and also hope you can comment more!!