一、数组的类型
1. 类型[ ]
var arr1: number[] = [1, 2, 3];
var arr2: string[] = ["1", "2"];
var arr3: any[] = [1, "2", true];
console.log(arr1,arr2,arr3);
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e1a98d8469940740e134e069dd21f680.png)
2. 数组泛型
let arr:Array<number> = [1,2,3,4,5]
console.log(arr);
3. 用接口表示数组
interface X {
name: string,
age?:number
}
let arr: X[] = [
{name: '小满'},
{name: '小青'}
]
console.log(arr);
4. 多维数组
let arr1:number[][] = [[1,2], [3,4]];
let arr2:Array<Array<number>> = [[1,2], [3,4]];
let arr3:any[] = [1, 'qwer', true, {}]
let arr4:[number, string, boolean, {}] = [1, 'qwer', true, {}]
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b916f6102d93b1699552e416be52ec8c.png)
5. arguments类数组
function Arr(...args:any): void {
console.log(...args)
console.log(arguments)
}
Arr(111, 222, 333)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9939da897ceabfc6256b5c75cc20e2ea.png)
function Arr(...args:any): void {
console.log(arguments)
let arr:IArguments = arguments
}
Arr(111, 222, 333)
interface IArguments {
length: number;
callee: Function;
[index: number]: any;
}
6. any 在数组中的应用
let list: any[] = ['test', 1, [],{a:1}]
console.log(list);
二、函数的类型
1.函数(箭头函数)定义类型和返回值
function add(a:number, b:number):number{
return a+ b
}
console.log(add(1,1));
const add = (a:number, b:number):number => a+ b
console.log(add(1,1));
2.函数默认的参数和函数可选参数
function add(a:number=10, b:number=20):number{
return a+ b
}
console.log(add(1));
const fn = (name: string, age?:number): string => {
return name + age
}
console.log(fn('张三'));
3.参数是一个对象如何定义
interface User{
name: string
age: number
}
function add(user:User){
return user
}
console.log(add({name: '张三', age: 18}));
4. 函数this类型
interface Obj {
user: number[]
add:(this:Obj, num:number) => void
}
let obj: Obj = {
user: [1, 2, 3],
add(this: Obj, num: number) {
this.user.push(num)
}
}
obj.add(4)
console.log('obj', obj);
5.函数重载
let user:number[] = [1,2,3]
function findNum(add: number[]):number[]
function findNum(id: number):number[]
function findNum():number[]
function findNum(ids?:number | number[]):number[]{
if(typeof ids == 'number'){
return user.filter(v=>v === ids)
}else if(Array.isArray(ids)){
user.push(...ids)
return user
}else{
return user
}
}
console.log(findNum());
console.log(findNum(3));
console.log(findNum([4,5,6]));
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/eccbb8578cfc3a960470a3f10d54225d.png)