基础类型
let a:string='hello';
let b:number=0;
let c:boolean=true;
let n:null=null;
let f:undefined=undefined;
数组
let array:number[]=[1,2,3,] //数组元素只能有一种类型
let array1:[number,string]=[1,'2'] //数组元素必须为以下类型
array1.push(true) //类型“boolean”的参数不能赋给类型“string | number”的参数
any类型
let c:any=11;
没有任何方法提示,因为是任意类型,无法判断类型。
联合类型
let c:string|number=1;
接口interface
接口其实就是人类共有的特征进行抽象,人都有鼻子眼睛。
let array:number[]=[1,2,3,] //数组元素只能有一种类型
let array1:[number,string]=[1,'2'] //数组元素必须为以下类型
array1.push(true) //类型“boolean”的参数不能赋给类型“string | number”的参数
interface IPeople{
eyes:string;
nose:string;
/**身份证号 ,只读属性,不能赋值 */
readonly id:number
money?:number
}
let people:IPeople={
eyes:'眼睛',
nose:"鼻子",
id:22233,
// money:11000,属性可有可无
}
people.id=22;//身份证号 ,只读属性,不能赋值无法分配到 "id" ,因为它是只读属性。
函数
const func1=(a:string,n:number):string=>{
return a+n
}
func1('2',2)
函数默认值,以及剩余参数
function func1(a='aa',...items:any[]){
console.log(items,'rest');
}
func1('a',33,4,5)
类Class
- 类:定义了一切事物的抽象特点。就好比一个汽车的车壳子
- 对象 :类的实例。一辆奔驰。
- 面向对象(OOP)封装,继承,多态。
封装
复杂代码进行封装,调用者只需要传参即可,无需了解函数实现过程。
多态
继承父类方法实现不同功能,
class Animal {
// private name: string;//设置属性为私有属性,字类无法访问,调用
// public name:string; 都可以访问
protected name:string;
constructor(name: string) {
this.name = name
}
run (){
return this.name+'run'
}
}
let animal=new Animal('张飞');
// animal.name 属性“name”受保护,只能在类“Animal”及其子类中访问。实例对象无法访问
class Cat extends Animal{
constructor(name:string){
super(name);
}
back(){
return 'aa'+ super.name
}
}
let cat=new Cat('猫');
console.log(cat.back());