美文网首页
学习typescript- Basic Types

学习typescript- Basic Types

作者: 土豪码农 | 来源:发表于2019-03-21 21:49 被阅读0次

    1.typescript基本声明类型有多少个种?分别怎么声明?

    • Boolean
    let isDone:boolead = false;
    
    • Number(不管是所有类型,浮点数,2进制,16进制,统一为number)
    let Num:number = 6; 
    
    • String
    let color:sring = "blue";
    
    • Array
    let list:number[] = [1,2,3];
    let list:Array<number> = [1,2,3];
    
    • Tuple
    let x:[string,number];
    x = ['22',22]  //ok
    x = [22,'22'] //ok
    x = ['sss', 222, 333, 'ssss']; //ok
    x = ['sss', 222, 333, 'ssss',true]; //err
    
    • Enum
    enum Color {Red, Green, Blus}  //default 0 ,1 ,2
    let c: Color = Color.Green;  //ok
    let c: Color = 222; //err
    
    enum Color {Red=1, Green, Blus}
    let c: Color = Color.Green; //2
    
    enum Color {Red=1, Green=4, Blus}
    let c: Color = Color.Green; //2
    
    enum Color {Red = 1, Green, Blus}
    let c: string = Color[2]; //Green
    
    • Any
    let a:any = 4;   //ok
    a = 'string';    //ok
    a = true;       //ok
    a = {};         //ok
    a = [];         //ok
    a = function () {
        //ok
    };
    const arr:any[] = [1,'1',true,{}]; //ok
    
    • void
    const fn = function ():void{
        true        //ok
    };
    
    const fn = function ():void{
        return 2      //err
    };
    
    let a:void = undefined; //ok
    let a:void = null; //ok
    
    • Undefined and Null
    let a:undefined = null;   //ok
    let a:undefined = undefined;   //ok
    let a:null = undefined;   //ok
    let a:null = null;   //ok
    
    • never
    //用于永远不会走到最后或者retrun error
    function error(message: string): never {
        throw new Error(message);  
    }
    
    function fail() {
        return error("Something failed");
    }
    
    function infiniteLoop(): never {
        while (true) {
        }
    }
    
    • object
    const obj:object = null; //ok
    const obj:object = {};   //ok
    
    • type assertions(断言)
    let obj = {};
    let num:number = obj ; //err
    
    let obj = {};
    let num:number = obj as number ; //ok
    let num:number = <number>obj ; //ok
    

    相关文章

      网友评论

          本文标题:学习typescript- Basic Types

          本文链接:https://www.haomeiwen.com/subject/kwlhvqtx.html