TypeScript语法
1.类型注解
-类型注解是变量后面约定类型的语法,用来约定类型,明确提示
// 约定变量 age 的类型为 number 类型
let age: number = 18;
age = 19;
TS数据类型
TS常用类型:
-JS已有类型
-简单类型,number string boolean null undefined
-复杂类型,对象 数组 函数
-TS新增类型
-联合类型、自定义类型(类型别口)、接口、元组、字面量类型、枚举、void、any、泛型 等
简单类型
完全按照JS的类型书写即可
let age: number = 18;
let myName: string = '王小明';
let isEating: boolean = false;
let nullValue: null = null;
let undefinedValue: undefined = undefined;
复杂类型
1.数组类型
// 写法一:(推荐)
let numbers: number[] = [1, 3, 5];
// 写法二:
let strings: Array<string> = ['a', 'b', 'c'];
2.对象类型
let obj : {name:string,age:number} = {name:'jack',age:18}
let person: {
name: string;
sayHi(): void;
} = {
name: 'jack',
sayHi() {},
};
3.额外内容
- 对象中的函数是箭头函数时
let person: { name: string sayHi: () => void } = { name: 'jack', sayHi() {}, };
- 对象中的属性是可选时,关键字是 ? ,例如axios中的get请求method就是可以省略
// axios({url,method}) 如果是 get 请求 method 可以省略 const axios = (config: { url: string; method?: string }) => {};
4.函数类型
// 普通函数
function add1(a: number, b: number): number {
return 1
}
// 函数表达式
const arr5 = function (a: number, b: number): number {
return a + b
}
const add = (a: number, b: number): number => {
return 1
}
// 箭头函数
const add2: () => string = () => {
return '1'
}