目录
typescript数据类型
基础数据类型
number、string、boolean、 null 和 undefined、object
//1.基础类型使用 // number:表示数值类型,例如:let age: number = 25; // string:表示字符串类型,例如:let name: string = "john"; // boolean:表示布尔类型,例如:let isready: boolean = true; // null 和 undefined:表示空值类型,例如:let data: null = null; // object:表示对象类型,例如:let person: object = { name: "john", age: 25 };\ export{} let n:number=18; let str:string="张三"; let b:boolean=true; let arr:number[]=[1,2,3]; let arr2:array<number>=[1,2,3]; let data:undefined=undefined; let data2:null=null; let data3:object={name:"张三",age:18};
其他数据类型
元组 []
类似数组。数组只能是一种数据类型,元组多个数据类型。但元组长度不能太长,不然不好理解。
//元组 let tuple:[number,string]=[18,"cts"];
枚举 enum
enum color{red,yellow,blue};
接口 interface
定义一组 属性(可以是数据类型或方法),不需要实现。可重复定义相同名称的接口,重名后将合并属性。
//接口 interface iperson { readonly id: number; name: string, age: number, color: color; address?:string, [propname: string]: any;//可以添加任意属性 } let tom: iperson = { id:1, name: 'tom', age:12, gender2:'male', color:color.red }; console.log(tom.age);
联合类型 |
类型可选择
let union:string|number; union=18; union="cts";
交叉类型 &
将多个类型合并成一个新的类型
interface iprintable { print(str:string): void; } interface iloggable { islog?:boolean; log(): void; } let c:iprintable & iloggable={ print(str:string){ console.log("printable") }, log(){ console.log("loggable") } }; c.print("你好呀");
type声明
- 1type 用于定义类型别名,使得我们可以为一个复杂类型或者一个较长的类型声明一个简短的别名。这个别名可以在任何地方使用,以代替原始的类型。
- 2.如果多次声明同一个变量、函数或类,这些声明会被自动合并为一个声明。这种合并称为声明合并。而 type 关键字也可以用于声明合并,允许我们扩展已有的类型声明。
type mystring = string; type point = { x: number; y: number }; type callback = (data: any) => void; let mystr:mystring="123"; type person2 = { name: string; } type user2 = { age: number; } let person: person2 & user2; person = { name: 'echo', age: 26, }
面向对象
类class
//定义类 class person{ name:string; age:number; address?:string;//?可为空 [propname: string]: any;//可以添加任意属性 constructor(name:string,age:number){ this.name=name; this.age=age; } sayhello():void{ console.log(`name:${this.name},age:${this.age}`); } } //类实例 let user:person=new person('rose',18); user.sayhello();
继承extends
class teacher extends person{ sayhello():void{ console.log( `teacher,name:${this.name},age:${this.age}`); } } let user2:person=new teacher('jack',18); user2.sayhello();
其他
类型推断
不添加变量或常量数据类型。
let num = 123; // 推断为 number 类型 console.log(num.tofixed(2)); // 输出:123.00
类型断言 as
将数据类型转换,常用any数据转换
let somevalue: any = "this is a string"; let strlength: number = (somevalue as string).length; console.log(strlength); // 输出:16
总结
类型是ts中最重要的部分,因为ts的诞生主要就是解决js弱类型的问题,增加了代码的可读性和可维护性。
引用
博文源代码https://github.com/chi8708/typescriptdemo/blob/main/basic2/01type.ts
发表评论