//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 Color{Red,Yellow,Blue};
定义一组 属性(可以是数据类型或方法),不需要实现。可重复定义相同名称的接口,重名后将合并属性。
//接口
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 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 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();
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
将数据类型转换,常用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