ts 数据类型:
布尔值:
let isDone:boolean=false;
数字:
let decLiteral:number=6;
字符串:
let name:string="bob"
数组:
let list:number[]=[1,2,3]
元组:Tuple
允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。 比如,你可以定义一对值分别为 string和number类型的元组。
let x:[string,number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error
枚举:
enum 枚举类型,为一组数值赋值名字;
enum Color={red,green,blue}
let c:Color=Color.red;
Any
编程阶段还不清楚类型的变量指定一个类型
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Void
表示没有返回值
function warnUser(): void {
console.log("This is my warning message");
}
Never
never类型表示的是那些永不存在的值的类型。
例如, never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型;
变量也可能是 never类型,当它们被永不为真的类型保护所约束时。
Object:
object表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
类型断言:
类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。
类型断言有两种形式。 其一是“尖括号”语法:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
另一个为as语法:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;