enum Direction{
Up = 10, //自动递增了
Down, //11
Left, //12
Right, //13
}
console.log(Direction.Up) //0
console.log(Direction[0]) //Up
泛型
function ecmaa<T>(args:T):T{
return arg
}
const str:string = 'str'; //指定后就不报错了下面的当然也可以去除不写这段类型推论会做的
const result = ecmaa(123)
function swap<T,U>(temp:[T,U]):[U,T]{
return [temp[1],temp[0]]
}
const result2 = swap(['string',123])
function ecmaWithArr<T>(arg:T[]):T[]{
console.log(arg.length)//我们不确定类型因此无法使用length属性,这样会报错如果不写T[]的话,但是我们写了的话解决方案也不是完美的,我们只能传入数组,但是对象或者简单类型的就会出问题
return arg
}
const arrs = ecmaWithArr([1,2,3])
interface IWithLength{
length:number
}
function ecmaWithLength<T extends IWithLength>(arg:T):T{
// 约束必须有length这个属性不然报错,这个解决泛型的方案就很棒 强烈推荐
console.log(arg.length) //
return arg
}
const str = ecmaWithLength('str');
const obj = ecmaWithLength({length:10,width:12});
const arr3 = ecmaWithLength([1,2,3]);
ecmaWithLength(12) //这样会报错,因为number没有length属性,泛型中使用特定的约束值不是想传什么就传什么
泛型在类中的使用
class Queue{
private data = [];
push(item){
return this.data.push(item)
}
pop(){
return this.data.shift()
}
}
//const queue = new Queue()
//这样会报错改为如下
const queue = new Queue<number>()
queue.push(1)
queue.push('str')
console.log(queue.pop().toFixed())
interface KeyPair{
key:T
value:U
}
let kp1:KeyPair<number,string> = {key:1,value:'string'}
let kp2:KeyPair<string,number> = {key:'str',value:3}
let arr:number[] = [1,2,3]
let arrTwo:Array<number>=[1,2,3]
type类型别名 使用交叉组合模型的时候使用
//平常我们声明个函数不可能声明都写这么长
let sum:(x:number,y:number)=>number
const result = sum(1,2)
//以上这样声明多个就比较多了重复的,那有个关键字
type PlusType = (x:number,y:number)=>number
let sum2:PlusType //这样就可以了是不是很简单
//还比如我们声明个变量
type StrOrNumber = string|number
let result:StrOrNumber = '111'
result =true //这样就报错了因为只能是字符串或者数字类型
type Directions = 'Up'|'Down'|'Left'|'Right'
let toWhere:Directions = 'Left'
interface IName{
name:string
}
type IPerson = IName & {age:number}
let person:IPerson = {name:‘123’,age:123}