一、靜態(tài)類型
使用了靜態(tài)類型,變量的類型不能改變,類型的屬性和方法也跟著確定。
interfaceXiaoJieJie{
uname:string,
age:number
}
?
constxiaohong:XiaoJieJie={
uname:'xiaohong',
age:18
}
基礎(chǔ)靜態(tài)類型
對(duì)象類型:對(duì)象、數(shù)組、類、函數(shù)
constcount:number=918;
constmyName:string='cq';
// null, undefined, boolean, void, symbol 基礎(chǔ)靜態(tài)類型
?
// 對(duì)象類型、數(shù)組、類、函數(shù)
constxiaojiejie: {
name:string,
age:number
}={
name:'cq',
age:23
}
?
constxiaojiejies:string[]=['cq1','cq2','cq3']
?
classPerson{ }
?
constdajiao:Person=newPerson()
?
constjianxiaojiejie: ()=>string=()=>{
return'dajiao'
}
二、類型注釋和類型推斷
類型注釋
letcount:number;
count=123
?
functiongetTotal(one:number,two:number) {
returnone+two;
}
consttotal=getTotal(1,2);
類型推斷
letone=1;
lettwo=2;
constthree=one+two;
?
constXiaojiejie={
name:'nancy',
age:23,
}
每個(gè)變量,每個(gè)對(duì)象的屬性都是固定的,如果能推斷就讓它推斷,推斷不出來(lái)的時(shí)候需要進(jìn)行類型注釋。
三、函數(shù)的參數(shù)定義和返回值定義
給函數(shù)的返回值加上類型注釋
// 數(shù)值類型返回值的函數(shù)
functiongetTotal5(one:number,two:number):number{
returnone+two;
}
?
// 沒(méi)有返回值的函數(shù)
functionsayHello():void{
console.log('hello');
}
?
// never返回值類型(執(zhí)行不完)
?
functionerrorFunction():never{
thrownewError();
console.log('hello');
}
?
functionforNever():never{
while(true) { }
console.log('hello');
}
函數(shù)參數(shù)為對(duì)象對(duì),需要解構(gòu)對(duì)類型進(jìn)行注釋
// 參數(shù)為對(duì)象
functionadd({one,two}: {one:number,two:number}) {
returnone+two;
}
四、數(shù)組類型的定義
一半數(shù)組類型的定義
constnumberArr:number[]=[1,2,3];
conststringArr:string[]=['1','2'];
constundefinedArr:undefined[]=[undefined];
constarr: (number|string)[]=[1,'111'];
數(shù)組中對(duì)象類型的定義
constxiaogege: {name:string,age:number}[]=[
?? {
name:'Jarry',
age:10,
?? },
?? {
name:'Tom',
age:8,
?? }
]
類型別名 type alias
typePeople={name:string,age:numebr};
classLady={
name:string;
age:number;
}
?
constxiaogege:People[]=[
?? {
name:'Jarry',
age:10,
?? }
]
?
constxiaojiejie:Lady[]=[
?? {
name:'Nancy',
age:15,
?? }
]
五、元組的使用和類型約束
元組可以把數(shù)組中每個(gè)元素類型的位置固定
constxiaojiejie: [string,string,number]=['dajiao','teacher',28]
元組的使用
constarray: [string,string,number][]=[
['a','b',12],
['c','d',19],
]
六、interface 接口
接口的定義和使用
interfaceBoy{
name:string;
age:number;
height:number;
waistline?:number;// 可選值
}
?
constscreenResume=(boy:Boy)=>{
const{age,name,height}=boy;
age<30&&height>180&&console.log(name+' pass');
(age>30||height<180)&&console.log(name+' refuse');
}
?
constgetResume=(boy:Boy)=>{
const{age,name,height,waistline}=boy;
console.log(name+'年齡是'+age);
console.log(name+'身高是'+height);
waistline&&console.log(name+'腰圍是'+waistline);
sex&&console.log(name+'性別是'+sex);
}
?
constboy={
name:'Tom',
age:28,
height:185,
}
screenResume(boy);
getResume(boy);
接口可以約束類
interfaceBoy{
name:string;
age:number;
height:number;
waistline?:number;// 可選值
[propname:string]:any,// key字符串類型,value任意類型
say():string,// say()方法,返回值為string類型
}
?
classXiaogegeimplementsBoy{
name:'LiuTao';
age:26;
height:183;
say: ()=>{
return'hello';
?? },
}
接口的繼承
// 接口的繼承
interfaceTeacherextendsBoy{
teach():string
}
constboy={
name:'Tom',
age:28,
height:185,
waistline:100,
sex:'男',
say: ()=>{
return'hello';
?? },
teach: ()=>{
return'teach';
?? }
}
七、類的概念和使用
類的基本使用和繼承
classLady{
content='hi';
sayHello() {
returnthis.content;
?? }
}
classXiaojiejieextendsLady{
// 重寫(xiě)父類的方法
/*? sayHello() {
? ? ? ? return 'hello';
? ? } */
?
// 重寫(xiě)并調(diào)用父類的方法
sayHello() {
returnsuper.sayHello()+' 你好';
?? }
sayLove() {
return'love you';
?? }
}
constNancy=newXiaojiejie();
console.log(Nancy.sayHello());
console.log(Nancy.sayLove());
八、類的訪問(wèn)類型
public? 公共的,默認(rèn)訪問(wèn)類型,允許在類的內(nèi)部和外部被調(diào)用
private? 私有的,只允許在類的內(nèi)部被調(diào)用
protected 被保護(hù)的,允許在類的內(nèi)部及繼承的子類中使用
classPerson{
protectedname:string;
publicsayHello() {
console.log(this.name+' say hello')
?? }
}
?
classTeacherextendsPerson{
publicsayBye() {
console.log(this.name+'say bye')
?? }
}
九、類的構(gòu)造函數(shù)
定義一個(gè)類,類里面有一個(gè)name,不給值。使用構(gòu)造函數(shù)在new出對(duì)象的時(shí)候,通過(guò)傳遞參數(shù)的形式,name賦值。
classPerson{
publicname:string
constructor(name:string){
this.name=name;
?? }
}
constperson=newPerson('cq')
?
// 簡(jiǎn)單的寫(xiě)法
?
clasaPerson{
constructor(publicname:string){}
}
類繼承中的構(gòu)造器寫(xiě)法,在子類中使用構(gòu)造函數(shù)必須用super調(diào)用父類的構(gòu)造函數(shù)。如果需要傳值,也必須進(jìn)行傳值操作。就算是父類沒(méi)有構(gòu)造函數(shù),子類也要使用super()進(jìn)行調(diào)用,否則會(huì)報(bào)錯(cuò)
classPerson{
constructor(publicname:string){}
}
classTeacherextendsPerson{
constructor(publicage:number){
super('cq')
?? }
}
?
constteacher=newTeacher(18)
十、TypeScript 類的Getter、Setter、static和readonly使用
用private封裝一個(gè)屬性,然后通過(guò)Getter和Setter的形式來(lái)訪問(wèn)和修改這個(gè)屬性。
classXiaojiejie{
constructor(private_age:number){
?? }
getage(){
returnthis._age-10;
?? }
setage(age:number){
this._age=age+3;
?? }
}
?
?
constdajiao=newXiaojiejie(28);
console.log(dajiao.age)18
?
// _age是私有的,類的外部沒(méi)辦法改變,可以用setter屬性進(jìn)行改變
dajiao.age=25;
console.log(dajiao.age);18
類中的static,用static聲明的屬性和方法,不需要進(jìn)行聲明對(duì)象,就可以直接使用。
classGirl(){
staticsayLove(){
return'Love you';
?? }
}
?
console.log(Girl.sayLove());
?
readonly只讀屬性,在實(shí)例化對(duì)象時(shí)賦值,以后不能再更改。
classPerson{
publicreadonly_name:string;
constructor(name:string){
this._name=name;
?? }
}
?
constperson=newPerson('cq');
// 報(bào)錯(cuò),因?yàn)開(kāi)name是只讀屬性,不能修改
person._name='cqq''
console.log(person._name);
十一、抽象類
抽象類跟父類很像,都需要繼承,但是抽象類中有抽象方法。繼承抽象類必須實(shí)現(xiàn)抽象方法才可以,抽象類的關(guān)鍵詞是abstract,里面的抽象方法也是abstract開(kāi)頭。
abstractclassGirl{
abstractskii()// 沒(méi)有具體的實(shí)現(xiàn)
}
?
classTeacherextendsGirl{
skill(){
console.log('教師')
?? }
}
?
classWaiterextendsGirl{
skill(){
console.log('服務(wù)員')
?? }
}
?
十二、聯(lián)合類型和類型保護(hù)
聯(lián)合類型:可以認(rèn)為一個(gè)變量可能有兩種或者兩種以上的類型。
interfaceWaiter{
anjiao:boolean;
say: ()=>{};
}
?
interfaceTeacher{
anjiao:boolean;
skill: ()=>{};
}
?
functionjudgeWho(animal:Waiter|Teacher){
// 報(bào)錯(cuò):因?yàn)閍nimal可能是Waiter可以能是Teacher
animal.say();
}
類型保護(hù)-類型斷言
interfaceWaiter{
anjiao:boolean;
say: ()=>{};
}
?
interfaceTeacher{
anjiao:boolean;
skill: ()=>{};
}
?
functionjudgeWho(animal:Waiter|Teacher){
if(animal.anjiao){
(animalasTeacher).skill()
? }
else{
(animalasWaiter).say();
?? }
}
?
類型保護(hù)-in語(yǔ)法
functionjudgeWho(animal:Waiter|Teacher){
if("skill"inanimal){
animal.skill();
}else{
animal.say();
?? }
}
類型保護(hù)-typeof語(yǔ)法
functionadd(first:string|number,second:string|number){
// 報(bào)錯(cuò):這兩個(gè)參數(shù)可能是數(shù)字,也可能是字符串,不做類型保護(hù)就相加會(huì)報(bào)錯(cuò)。
returnfirst+second;
}
?
functionadd(first:string|number,second:string|number){
// 使用typeof解決
if(typeoffirst==='string'||typeofsecord==='string'){
return`${first}${second}`;
?? }
returnfirst+second;
}
類型保護(hù)-instanceof語(yǔ)法
// 如果類型保護(hù)一個(gè)對(duì)象,使用instanceof語(yǔ)法
classNUmberObj{
count:number;
}
functionaddObj(first:object|numberObj,second:object|numberObj){
if(firstinstanceofNumberObj&&secondinstanceofNumberObj){
returnfirst.count+second.count;
?? }
return0;
}
十三、TypeScript? 函數(shù)泛型-難點(diǎn)
generic? 通用、泛指的意思,泛型使用<>定義。
給join方法一個(gè)泛型,名字隨便起,后邊的參數(shù)也是用泛型的名稱。在正式調(diào)用這個(gè)方法的時(shí)候,具體指明泛型的類型。
functionjoin<T>(first:T,second:T){
return`${first}${second}`;
}
join<string>('baidu','com')
泛型中數(shù)組的使用,第一種直接使用[],第二種使用Array<泛型>
functionmyFun<ANY>(paramsANY[]){
returnparams;
}
?
// 第二種寫(xiě)法
functionmyFun<ANY>(paramsArray<ANY>){
returnparams;
}
?
myFun<string>['123','234'];
多個(gè)泛型的定義
functionjoin<T,P>(first:T,second:P){
return`${first}${second}`
}
join<number,string>(1,'2')
泛型的類型推斷
functionjoin<T,P>(first:T,second:P){
return`${first}${second}`
}
join(1,'2');
十四、TypeScript? 類中泛型-難點(diǎn)
classSelectGirl<T>{
constructor(privategirls:T[]){}
getGirl(index:number):T{
returnthis.girls[index];
?? }
}
constselectGirl=newSelectGirl()<string>['q','d','h']
泛型中的繼承
interfaceGirl{
name:'string';
}
?
classSelectGirl<TextendsGirl>{
constructor(privategirls:T[]){}
getGirl(index:number):string{
returnthis.girls[index].name;
?? }
}
?
constselectGirl=newSelectGirl([
{name:'a'},
{name:'b'},
{name:'c'},
])
?
console.log(selectGirl.getGirl(1));
泛型的約束
classSelectGirl<Textendsnumber|string>{
constructor(privategirls:T[]){}
getGirl(index:number):T{
returnthis.girls[index];
?? }
}
constselectGirl=newSelectGirl<string>(['a','b','c')
console.log(selectGirl.getGirl[1]);