ts中enum枚举类型

 

枚举类型

enum sex {
   male = "男",
   female = "女",
   unknown = "未知",
 }

 

//数字型枚举

enum color {
   red = 10,
   green,
   yellow, 
}
console.log(color.green) //11
console.log(color.yellow) //12

 

//易构型枚举

enum obj{
   up = "上",
   green = 10, 
}

 

//常量型 枚举(成员类型值不能为变量)

let unfind = 404;
enum sta {
  success = 200,
  unfound = unfind,
  fail = 500,
}
console.log(sta);

 

枚举的合并,他不会覆盖 会直接合并

enum sex{
    ci = "雌",
    xiong = "雄",
}
enum sex {
  male = "男",
  female = "女",
  unknown = "未知",
}
console.log(sex)

 

函数的使用

m的值必须是string n的值必须是number

 

function fn(m:string,n:number):string{
return `${m} am ${n} years old forever`
}
console.log(fn("I",18))  //I am 18 years old forever

//1.可选参数
let f1 = (m:string,n?:number):string=>{
    return `${m}---${n}`
}
console.log(f1("I"))

 

2.默认参数

多余参数可以写到一起

let f1 = (m:string,like:string="羽毛球",n?:number,...arr:any[]):string=>{
   console.log(arr)
    return `${m}--${n}--${like}`
}
console.log(f1("我",'篮球',18,'baby','love'))

 

函数得重载(重点)

let f3 = (m:string|number):string|number=>{
}
function f3(m: string): string;
function f3(m: number): number;
function f3(m: boolean): boolean;
function f3(m: string | number | boolean): any {
//   console.log(typeof m);
  if(typeof m =="string"){
      return `我是${m}`
  }
  if(typeof m =="number"){
      return m
  }
  if(typeof m =="boolean"){
      return `判断${m}`
  }
}
console.log(f3("最棒的"))
console.log(f3(18))
console.log(f3(true))

 

 

 

 

你可能感兴趣的:(ts常见的基本数据类型,typescript)