TypeScript-2

二、进阶

1.类型别名

类型别名用来给一个类型起个新名字。

type name=string;
type nameFn=()=>string;

function test(n:name|nameFn):name{
    if(typeof n=='string'){
        return n;
    }else{
        return n();
    }
}

2.字符串字面量类型

用来约束取值只能是某几个字符串中的一个。

类型别名与字符串字面量类型都是使用 type 进行定义。

type EventNames='click'|'scroll'|'mousemove';
function handleEvent(el:Element,event:EventNames){

}
handleEvent(document.body,'scroll');
handleEvent(document.body,'dbclick');//error : Argument of type '"dbclick"' is not assignable to parameter of type 'EventNames'.

3.元组

数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。

let list:[string,number]=['aa',2];

// 当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。
 let list1:[string,number]=['aa'];//error:Type '[string]' is not assignable to type '[string, number]'.
 
 

猜你喜欢

转载自www.cnblogs.com/yuesu/p/9983529.html