Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
99 lines (80 sloc) 2.04 KB
/**
* Boolean
*/
let isBool: boolean = false;
// isBool = 'test'; // Error:(3, 1) TS2322: Type '"test"' is not assignable to type 'boolean'.
isBool = true; // ok
// console.log('this is ts boolean varible', isBool);
/**
* String
*/
let isStr: string = 'test';
// isStr = 1; // error
isStr = 'new test';
// console.log(isStr);
/**
* Number
*/
let isNum: number = 1;
// isNum = 'test'; // error
isNum = 11;
// console.log(isNum);
/**
* Array
*/
// 中括号
let arrNormal: any[] = [1, '2', true, {}];
// console.log(arrNormal);
// 类似 JavaScript的 new Array
let arrCst: Array<any> = [1, '2', true, {}];
// console.log(arrCst);
let arrDef: any = [];
arrDef.push('test');
arrDef.push(1);
// console.log(arrDef);
// 只能放数字元素的数组
let arrInt: number[] = [];
// arrInt.push('test'); // error
arrInt.push(1); // ok
// console.log(arrInt);
// 这种声明的方式,在声明时,等于限制了数组个数,并且每个位置的元素的类型,但声明之后可以随便修改,但类型必须属于声明的类型
let arrIntStr: [string, number];
arrIntStr = ['str', 1]; // 必须第一个string,第二个number,不能变,也不能改变加或减元素
arrIntStr.push('test'); // 可以增加
// arrIntStr.push(true); // error 类型不支持
// arrIntStr[0] = 0; // error 前两天的类型已经被定了,不能改变
// console.log(arrIntStr);
/**
* 枚举
*/
enum Color {
Red,
Green = 3, // 如果某个设置了值,后面的将接着排序
Blue
}
// console.log(Color);
const c: String = Color[3];
const cIndex: Number = Color.Green;
// console.log(c, cIndex); // 'Green', 3
/**
* 任意值关键字:any
*/
let vir:any = 3;
vir = 'test';
vir = true;
// console.log(vir); // ok
/**
* 空值关键字:void 只能是null和undefined
*/
let unabled: void = null;
unabled = undefined;
// unabled = 'test'; // error
// console.log(unabled);
/**
* 类型断言
*/
let some: any = 'test';
let len: number = (some).length;
some = true;
let len2: number = (<string>some).length;
console.log(some, len, len2);
You can’t perform that action at this time.