类和接口的区别:接口中只声明成员方法,不做实现;类声明并实现方法。
//属性接口 interface Config { color ?: string; number; [propName: string]: any; } function test(value: Config){ console.log(value); } test({ color: 'white', //color属性可以省略不写 600, height: 50 });
//函数类型接口 interface FunctionConfig { (source: string, subString: string): string; } let myFunction: FunctionConfig; myFunction = function(s1: string, s2: string): string{ return (s1+s2); }; console.log(myFunction('hello', ',www'));
//可索引接口 interface UserArray { [index: number]: string; } let arr1: UserArray = ['aaa', 'bbb']; console.log(arr1);
类:
//类 class A { name: string; constructor(message: string) { this.name = message; } sayName(){ return this.name; } } class B extends A { constructor(name: string){ super(name); } sayHi(){ return 'Hello,'+this.name; } } let a = new A('John'); let b = new B('Sunny'); console.log(a.sayName()); console.log(b.sayName()); console.log(b.sayHi());
//公有属性、私有属性、受保护的修饰符 abstract class C { constructor(public name: string){} public sayHi(){ return 'History'; } } class D extends C { static origin = 11; constructor (name: string){ super(name); } public sayName() { return this.name+D.origin; } } let d = new D('hello'); console.log(d.sayName());
//抽象类-抽象类一般不会被实例化,做为其他派生类的基类使用 //抽象类中的抽象方法不包含具体的实现,并且必须在派生类中实现 abstract class Media { constructor(public name: string){} abstract sayName(): void; } class Phone extends Media { constructor(name: string){ super(name); } sayName(){ return 'Haha'+this.name; } } let e = new Phone('John'); console.log(e.sayName());