1.数据类型
ts中对于没有返回值的函数可以用void来表示
function Test: void {
console.log('this is a no return result of funciton')
}
思考一:void和undefined和null的区别?
在ts中undefined和null可以是任何类型的子类型,可以赋值给任何类型的变量 不能将void类型赋值给普通变量
联合类型 用于变量的类型有多种
const maxHeight: string | number
interface IProps {
readonly title: string //只读属性
size?: number //可选参数
[key:string]: any //任意类型
}
const props:IProps {
title: 'this is title',
size: 20
}
注意:接口也可以用来约束数组,但是不建议这么去做,比较麻烦,如下:
interface INumberArray {
[index: number]: number <!--用索引类型来约束值的类型-->
}
const number: INumberArray = [1,2,3]
建议使用type来约束数组类型
type INumberArray = Array<number>
数组类型:
1> elemType[]
2> Array<elemType>
函数的类型
function sum(x: number,y: number = 2,z?: number): number{
return x + y
}
//同样可以用...reset来表示剩余参数
function push(array: any[], ...items: any[]) {
items.forEach(function(item) {
array.push(item)
});
}
2.类型断言
可以理解为强制更改类型 类型断言只会影响编译时的类型,类型断言语句在编译结果中会被删除 类型断言不是类型转换,它不会真的影响到变量的类型
(window as any).foo = 1
3.双重断言
思想:任何类型可以断言为any any可以断言为任何类型
interface Cat {
run(): void
}
interface Fish {
swim(): void
}
function testCat(cat: Cat) {
return (cat as any as Fish)
}
4.元组
思想:合并了不同类型的对象
let tom: [string, number] = ['Tom', 25]
5.泛型
思想:约定输入类型和输出类型一致
function sum<T>(x: T, y: T): T{
return x + y
}