typescript数据类型:
any:声明为 any 的变量可以赋予任意类型的值。
number:声明为 number 的变量可以赋予数字类型的值(二进制八进制十进制十六进制)
string:声明为 string 的变量可以赋予字符串类型的值或者反引号(`)来定义多行文本和内嵌表达式:
let words: string = `您好,今年是 ${ name } 发布 ${ years + 1} 周年`;
boolean:声明为 boolean 的变量可以赋予true 和 false
数组:声明变量为数组。
第一种是在元素类型后面加上[]:
let arr:number[] = [1,2,3,4,5,6]
第二种是数组泛型:
let arr: Array<number> = [1,2,3,4,5,6]
null和undefined
null 和 undefined 可以作为其它类型的子类型(前提是把config.json文件中的严格模式"strict" 设置为false) 例如:
var kk: number = undefined
var kk2: string = null
never:never 是其它类型(包括 null 和 undefined)的子类型,代表从不会出现的值。这意味着声明为 never 类型的变量只能被 never 类型所赋值,在函数中它通常表现为抛出异常或无法执行到终止点(例如无限循环)。
let x: never;
let y: number;
x = 123; // 运行错误,数字类型不能转为 never 类型
x = (()=>{ throw new Error('exception')})(); // 运行正确,never 类型可以赋值给 never类型
y = (()=>{ throw new Error('exception')})(); // 运行正确,never 类型可以赋值给 数字类型
function error(message: string): never { throw new Error(message);} // 返回值为 never 的函数可以是抛出异常的情况
function loop(): never { while (true) {}} // 返回值为 never 的函数可以是无法被执行到的终止点的情况
元组
元组中允许存储不同数据类型的元素,元组可以作为参数传递给函数。
let tup:[string,number,boolean] = ['kzt',12,false]//元组
let tup2= ['kzt',12,false]//元组
var en = tup.push('tmac',24) //push() 向元组添加元素,添加在最后面。并返回新的长度。
tup2.pop()//pop() 从元组中移除元素(最后一个),并返回移除的元素。
console.log(en) //5
console.log(tup2)//['kzt',12]
枚举 (enum)
定义一个Color枚举类型。3个元素red,blue,green。元素不定义值默认是以0开始,然后元素值递增1。若其中一个元素定义了值,从这个元素开始后面没有定义值的元素的元素值递增1。若已知元素值,要访问对应的元素,用枚举名[ 元素值]
enum Color{
red, //0
blue, //1
green=21,
gray //22
}
var cor = Color.red;
console.log(cor) //0
console.log(Color[1]) //blue
console.log(Color.gray) //22
void:用于标识方法返回值的类型,void表示该方法没有返回值。
function hello(): void { alert("Hello Runoob");}
联合类型:可以用 | 来支持多种类型,例如:
let x : number | null | undefined;
x = 1; // 运行正确 x= null; // 运行正确 x= undefined; // 运行正确