1. class Greeter {
  2. greeting: string
  3. constructor(message: string) {
  4. this.greeting = message
  5. }
  6. greet() {
  7. return `Hello,${this.greeting}`
  8. }
  9. }
  10. let greeter = new Greeter('world')

继承

  1. class Animal {
  2. move(s: number = 0) {
  3. console.log(`Animal moved ${s}m.`);
  4. }
  5. }
  6. class Dog extends Animal {
  7. bark() {
  8. console.log('woof! woof!');
  9. }
  10. }
  11. const dog = new Dog()
  12. dog.bark()
  13. dog.move(10)
  14. dog.bark()
  15. class Animal {
  16. name: string;
  17. constructor(theName: string) { this.name = theName; }
  18. move(distanceInMeters: number = 0) {
  19. console.log(`${this.name} moved ${distanceInMeters}m.`);
  20. }
  21. }
  22. class Snake extends Animal {
  23. constructor(name: string) { super(name); }
  24. move(distanceInMeters = 5) {
  25. console.log("Slithering...");
  26. super.move(distanceInMeters);
  27. }
  28. }
  29. class Horse extends Animal {
  30. constructor(name: string) { super(name); }
  31. move(distanceInMeters = 45) {
  32. console.log("Galloping...");
  33. super.move(distanceInMeters);
  34. }
  35. }
  36. let sam = new Snake("Sammy the Python");
  37. let tom: Animal = new Horse("Tommy the Palomino");
  38. sam.move();
  39. tom.move(34);
  40. // Slithering...
  41. // Sammy the Python moved 5m.
  42. // Galloping...
  43. // Tommy the Palomino moved 34m.
  44. public private readonly
  45. class Animal {
  46. private name: string
  47. public age: number
  48. readonly money: number
  49. constructor(theName: string) {
  50. this.name = theName
  51. this.age = 18
  52. }
  53. }
  54. class Rhino extends Animal {
  55. constructor() { super("Rhino"); }
  56. }
  57. class Employee {
  58. private name: string;
  59. constructor(theName: string) { this.name = theName; }
  60. }
  61. // new Animal('nn').name //私有的无法访问
  62. let animal = new Animal("Goat");
  63. let rhino = new Rhino();
  64. let employee = new Employee("Bob");
  65. // animal.money = 100 // error 只读不能修改
  66. animal = rhino;
  67. // animal = employee; // 错误: Animal 与 Employee 不兼容.

protected 静态属性

  1. class Person {
  2. protected name: string
  3. static color: string
  4. constructor(name: string) {
  5. this.name = name
  6. }
  7. greet(){
  8. return Person.color
  9. }
  10. }
  11. class Employee extends Person {
  12. private department: string
  13. constructor(name: string, department: string) {
  14. super(name)
  15. this.department = department
  16. }
  17. public getElevatorPitch() {
  18. return `my name is ${this.name} and I work in ${this.department}`
  19. }
  20. }
  21. let xiaoming = new Employee('xiaoming','shop')
  22. console.log(xiaoming.getElevatorPitch());
  23. // console.log(xiaoming.name); //属性“name”受保护,只能在类“Person”及其子类中访问。

把类当做接口使用

  1. class Point {
  2. x: number;
  3. y: number;
  4. }
  5. interface Point3d extends Point {
  6. z: number;
  7. }
  8. let point3d: Point3d = { x: 1, y: 2, z: 3 };