Type annotation
We all know that JavaScript is a weakly typed language. Weakly typed languages are not good for our standardized development process. Type annotations are a solution proposed by TypeScript to strengthen language types. Therefore, TypeScript is also a strongly typed language.
For example, if we define a variable age to be of type number, then we cannot attach a value of another type to it.
let age: number;
age = 123;
As shown in the above example, the type annotation in TypeScript is to use the ":" keyword, and the declaration can be completed by: + data type
type of data | Key words |
---|---|
String | string |
Number | number |
Boolean | boolean |
Void | void |
Any | any |
Undefined | undefined |
Null | null |
1. Array type annotation
Uniform type in array
const arr: number[] = [1, 2, 3];
The types in the array are not uniform
const arr: (number | string)[] = [1, "string", 2];
Object array
const student: { name: string, age: number }[] = [
{ name: "小白", age: 21 },
{ name: "小黑", age: 18 },
];
2. The use of tuples
The lack of array
When we are using an array to process a business, if the order of the elements in the array is changed, then our business logic will have an error, but the type annotation of the array will not report an error. At this time, we will use the tuple type Comment (type constraint).
// 如果数组中的元素顺序发生变化,数组的类型注释不报错,存在开发隐患
const beauty1: (string | number)[] = ["A", "student", 18]
const beauty2: (string | number)[] = ["A", 18, "student"]
// 使用元组中的类型约束可以解决此隐患
const beauties1: [string, string, number] = ["A", "student", 18]
const beauties2: [string, string, number] = ["A", 18, "student"] //报错!