2016-09-02 31 views
0

我有這樣的代碼:打字稿我可以使用類一樣的界面

interface Heroe { 
    title:string, 
    hero:string, 
    ranking:number, 
} 

export class AppComponent { 
    heroe : Heroe = { 
    title : 'Tour of Heroes', 
    hero : 'Windstorm', 
    ranking :1 
    } 
} 

如果我更換類,而不是接口的代碼工作:

class Heroe { 
    title:string, 
    hero:string, 
    ranking:number, 
} 

export class AppComponent { 
    heroe : Heroe = { 
    title : 'Tour of Heroes', 
    hero : 'Windstorm', 
    ranking :1 
    } 
} 

它的正確使用類接口等,上課時有沒有方法,只是類型的變量,那不是問題?在角演示用這種方式,有一個類,而不是接口:

https://angular.io/docs/ts/latest/tutorial/toh-pt1.html

在這最後的情況下,我有一個類,而不是接口,並有類無接口,

正確不會先有接口,然後一個基於接口的類? ,但是如果兩者具有相同的名稱;如何使用打字稿?

例子:

interface Heroe { 
    title:string, 
    hero:string, 
    ranking:number, 
} 
class Heroe interface Heroe { 
    title:string, 
    hero:string, 
    ranking:number, 
} 

export class AppComponent { 
    heroe : Heroe = { 
    title : 'Tour of Heroes', 
    hero : 'Windstorm', 
    ranking :1 
    } 
} 

我的好也有英雄同名類一樣的界面?

回答

2

「這是正確使用類接口等」
嗯,這取決於你想要做什麼,但它是不一樣的:

class Heroe { 
    title: string; 
    hero: string; 
    ranking: number; 

    constructor(title: string, hero: string, ranking: number) { 
     this.title = title; 
     this.hero = hero; 
     this.ranking = ranking; 
    } 
} 

let o1 = new Heroe("title", "hero", 0); 
let o2: Heroe = { title: "title", hero: "hero", ranking: 0 } 

編譯成:

var Heroe = (function() { 
    function Heroe(title, hero, ranking) { 
     this.title = title; 
     this.hero = hero; 
     this.ranking = ranking; 
    } 
    return Heroe; 
}()); 
var o1 = new Heroe("title", "hero", 0); 
var o2 = { title: "title", hero: "hero", ranking: 0 }; 

code in playground

正如你可以看到o1o2明顯不同,一個是我Heroe類的實例,第二個只是與實例屬性相同的對象。

這是在控制檯中明確:

console.log(o1); // Heroe {title: "title", hero: "hero", ranking: 0} 
console.log(o2); // Object {title: "title", hero: "hero", ranking: 0} 

,編譯器不關心o2只是一個對象甚至宣稱,當其原因爲Heroeis because

一個打字稿的核心原則這種類型檢查的重點在於數值所具有的形狀。這有時稱爲「鴨子打字」或 「結構分型」。

more about Duck typing

或者用一個例子:

function log(heroe: Heroe) { 
    console.log(`Title: ${ heroe.title }, Hero: ${ heroe.hero }, Ranking: ${ heroe.ranking }`); 
} 

log(o1); // obviously this is ok 
log(o2); // but this is ok as well 

傳遞o2是好的,因爲即使它不是Heroe實例它確實滿足了接口的類。


您可以使用相同的名稱爲一個接口和一個類,但你不能重新聲明屬性,所以這是不正常:

interface Heroe { 
    title: string; // Error: Duplicate identifier 'title' 
} 

class Heroe { 
    title: string; // Error: Duplicate identifier 'title' 
} 

但這是:

接口Heroe { title:string; }

class Heroe { subtitle:string; }

聲明的順序並不重要,你可以在類下面有接口。
你可以在Declaration Merging瞭解更多。

但你也可以實現一個接口:

interface IHeroe { 
    title: string; 
    hero: string; 
    ranking: number; 
} 

class Heroe implements IHeroe { 
    title: string; 
    hero: string; 
    ranking: number; 
} 
+0

多麼偉大的答案! – creativeChips