class Person {// 类的属性
name: string;
age: number;// 构造函数,并指定参数类型 constructor(name: string, age: number){
this.name = name;
this.age = age;}// 类的其他方法... greet(){
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);}}// 创建一个Person对象
let person = new Person('Alice',30);// 正确 // let person2 = new Person(30, 'Alice'); // 错误:第一个参数应该是字符串,但得到了数字
2. 在类中指定泛型参数
class GenericBox<T>{
private value: T;constructor(value: T){
this.value = value;}getValue(): T {return this.value;}setValue(newValue: T):void{
this.value = newValue;}}// 使用 string 类型的泛型参数实例化类
let stringBox = new GenericBox<string>("Hello, world!");
console.log(stringBox.getValue());// 输出 "Hello, world!" // 如果不指定泛型参数,TypeScript 会尝试进行类型推断
let autoBox = new GenericBox("Hello again!");// 类型被推断为 string
console.log(autoBox.getValue());// 输出 "Hello again!" // 但如果你试图传递错误的类型,TypeScript 会报错 // let errorBox = new GenericBox<string>(42); // 编译错误:Type '42' is not assignable to type 'string'.
综合示例
let passcode ="secret passcode";
class Animal {// 在TypeScript里,成员都默认为 public
public name: string;// private name: string;
protected name2: string;// 使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
readonly password: string;
private _fullName: string;
public constructor(theName: string){ this.name = theName;}
public move(distanceInMeters: number =0){
console.log(`${this.name} moved ${distanceInMeters}m.`);}// TypeScript支持通过getters/setters来截取对对象成员的访问。 // 它能帮助你有效的控制对对象成员的访问。
get fullName(): string {return this._fullName;}
set fullName(newName: string){if(passcode && passcode =="secret passcode"){
this._fullName = newName;}else{
console.log("Error: Unauthorized update of employee!");}}// // 类的静态成员,这些属性存在于类本身上面而不是类的实例上// static origin = {x: 0, y: 0};// calculateDistanceFromOrigin(point: {x: number; y: number;}) {// let xDist = (point.x - Grid.origin.x);// let yDist = (point.y - Grid.origin.y);// return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;// }}// // 当成员被标记成 private时,它就不能在声明它的类的外部访问。比如:// new Animal("Cat").name; // 错误: 'name' 是私有的.// 继承
class Snake extends Animal {// 在构造函数里访问 this的属性之前,我们 一定要调用 super()。// 这个是TypeScript强制执行的一条重要规则。constructor(name2: string){super(name2);}move(distanceInMeters =5){
console.log("Slithering...");
super.move(distanceInMeters);}getElevatorPitch(){// protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问。return `Hello, my name is ${this.name2} `;}}
class Horse extends Animal {constructor(name: string){super(name);}move(distanceInMeters =45){
console.log("Galloping...");
super.move(distanceInMeters);}}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);// 抽象类用abstract