typescript1-Basic Types

Refenerce:https://www.typescriptlang.org/docs/handbook/basic-types.html

basic type:
boolean
let isDone:boolean=true;


number 在typescript中,所有的number类型都是浮点型的,也可以是十六进制或则八进制
let decimal:number=6;
let hex:number=0xfff;

string
let color:string="blue";
也可以使用字符串模板,格式是${变量}
let a:string="blue";
let b:string=${a}123;

array

数组的话,有两种写法
let colors:number[] = [1,2,3];
let colors2:Array =[1,2,3];

元祖 tuple
就是声明了固定的数量的元素类型
let x:[string,number]=["hello",10];
let x1:[string,numer]=[10,"hello"];这是错误的,一定要按照顺序来
访问的时候,通过索引下标进行访问
console.log(x[0].substr(1)),因为是字符串,所以有substr方法,要对应类型使用自己的方法
note:我们还可以给元祖赋值,但是赋值的类型要是刚才定义的,string或则number
x[6]=123;x[8]="hello";x[9]=false这就是错误的,没有定义boolean值

enum 枚举
一个好像很神奇的语法,可以将里面的元素和潜在的索引值绑定,并相互反转,组成一个对象
例如 enum Color {red,green,purple};
console.log(Color.red);
编译之后会是这样

中间部分的对象.键=值的结果是返回值,然后将值又做为键,重新赋值添加到对象中
note:默认的索引是从零开始的,但是我们可以手动设置自己想要的索引,例如

访问的时候,我们也可以
enum Color {red=1,green,purple}
let colorName:string =Color[2];
console.log(colorName);

Any 在开发中我们可能不知道具体的类型是什么的时候,我们可以定义类型为any,
let h: any = 123;
h = true;
h="haha"
当any的类型是一个数组的时候,我们可以这样
let list:any[] =[1,"asa",false];
list[1]=100;

void 空类型
function abcd():void{
console.log(133);
}
或则在undefined或null的值的时候使用
let k:void = undefined;

never
表示该值类型不会再发生了,多数发生在错误函数中

// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

// Inferred return type is never
function fail() {
    return error("Something failed");
}

// Function returning never must have unreachable end point
function infiniteLoop(): never {
    while (true) {
    }
}

Object
let bb: Object =

类型主张
假设我们知道或许操作的类型比编译器知道的情况,我们可以使用自己的方式执行下去
let ads:string="123";
let length123:number =(ads).length;
或则:
let asqwe:string="456465";
let length789 = (asqwe as string).length;
note:如果使用jsx语法的话,只能使用第二种方式

posted @ 2018-09-16 10:56  cyany_blue  阅读(245)  评论(0)    收藏  举报