typescript中類和接口的區別


類和接口的區別:接口中只聲明成員方法,不做實現;類聲明並實現方法。
//屬性接口
interface Config {
    color ?: string;
    width: number;
    [propName: string]: any;
}
function test(value: Config){
    console.log(value);
}
test({
    color: 'white', //color屬性可以省略不寫
    width: 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());

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM