let nameSub = "xx"; //类型推论 let title: string; //类型注解 // nameSub = 2; // title = 4; title = "TS"; // 数组类型 let names: string[]; names = [‘tom‘,‘mary‘]; // 任意类型 let foo: any = ‘xxx‘; foo = 2; // 任意类型用于数组 let list: any[] = [1,‘aaa‘]; // 多种类型 let multiType: string | number; multiType = 2; multiType = ‘aaa‘; // 多个值约定 let multiVal: 1 | 2; multiVal = 2; // 类型用于函数,规定函数返回值的类型 function greeting(person: string): string { return ‘aaa‘; } // 无返回值 function greeting2(msg: string): void { alert(22); } // 内置类型 // string, number, boolean, void, any // 函数的参数如果声明,就是必须有参数,所以调用时类型和数量必须满足 // 并且如果约束了函数的类型,则必须有返回值 // 参数里面的?表示可选参数 function sayHello(name:string, age:number, sex?: string): string{ console.log(name,age); return ‘aaa‘; } sayHello(‘tom‘,12); // sayHello(‘tom‘); // sayHello(11,12); // 函数重载:先声明,再实现 // 根据参数(数量,类型)不同返回不同的结果 // 声明1 function info(a: object): string; // 声明2 function info(a: string): object; // 实现 function info(a: any): any{ if(typeof a == "object"){ return a.name; }else{ return { name: a}; } } console.log(info({name:"tom"})); console.log(info(‘tom‘)); // ts中的class class MyComp { // 访问修饰符private、public、protected,默认public private _foo: string; //私有属性,不能在类的外部访问 protected bar: string; //保护属性,还可以再派生类中访问 readonly mua = ‘mua‘; //只读属性必须在声明时或构造函数里初始化 // 构造函数:初始化成员变量 // 参数加上修饰符,能够定义并初始化一个成员属性,相当于在上面定义的变量 constructor(private tua = ‘tua‘,foo=‘foo‘,bar = ‘bar‘){ // 赋值 this._foo = foo; this.bar = bar; } // 方法也有修饰符 private someMethod(){ } // 存取器:存取数据时可添加额外逻辑,在vue里面可以用作计算属性 get foo(){ return this._foo; } set foo(val){ this._foo = val; } } // 接口: 接口仅约束结构,不要求实现,使用简单 interface Person1{ firstName: string; lastName:string; } function getNameAll(person:Person1):string{ return ‘Hello, ‘ + person.firstName + ‘ ‘ + person.lastName; } const user = { firstName:‘Jane‘, lastName:‘user‘, }; console.log(getNameAll(user)); // 接口 interface Person { firstName: string; //要求有firstName属性 lastName: string; //要求有lastName属性 sayHello(): string; //要求实现sayHello方法 } // 类实现接口 class Greeter implements Person { constructor(public firstName=‘‘,public lastName=‘‘){} sayHello(){ return ‘Hello, ‘ + this.firstName + this.lastName; } } // 面向接口编程(函数) function greetingGo(person: Person) { return person.sayHello(); } const user2 = new Greeter(‘Jane‘, ‘User‘); // 创建对象实例 console.log(greetingGo(user2)) // 泛型 // 泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型, // 而在使用的时候再指定类型的一种特性。以此增加代码的通用性 // 不用泛型 interface Result { ok: 0 | 1; data: Feature[]; } // 使用泛型 // 此时data字段的类型就灵活了,有使用传入的参数T约束 interface Result<T> { ok: 0 | 1; data: T[]; } // 装饰器 // 装饰器用于扩展类或者他的属性和方法,写法@xxx // 原理就是一个工厂函数,通过定义劫持,能够对类及其方法、属性提供额外的扩展功能 // 组件声明:@Component @Component export default class Hello extends Vue {} // @Component还可以函数形式传入配置 @Component({ props:{ msg:{ type:String, default:‘msg‘ } } })
原文:https://www.cnblogs.com/gopark/p/12333509.html