2017-10-11 67 views
1

在這種情況下使用'any'而不是接口是否有任何缺點?接口x任何

首先與項目的接口:

imports ... 
export interface Item { name: string; } 

@Component({ 
    selector: 'app-root', 
    template: ` 
    my template 
    ` 
}) 
export class AppComponent { 
    private itemsCollection: AngularFirestoreCollection<Item>; 
    items: Observable<Item[]>; 
    constructor(private afs: AngularFirestore) { 
    this.itemsCollection = afs.collection<Item>('items'); 
    this.items = this.itemsCollection.valueChanges(); 
    } 
} 

沒有接口,與 '任意'

imports... 

@Component({ 
    selector: 'app-root', 
    template: ` 
    my template 
    ` 
}) 
export class AppComponent { 
    private itemsCollection: AngularFirestoreCollection<any>; 
    items: Observable<Any[]>; 
    constructor(private afs: AngularFirestore) { 
    this.itemsCollection = afs.collection<any>('items'); 
    this.items = this.itemsCollection.valueChanges(); 
    } 
} 

謝謝

回答

0

在這種情況下使用any是一種不好的做法。基本上,你扔掉了TypeScript最重要的部分之一(which is type system)及其好處(編譯時類型檢查)。做不是做它,除非它是必要的。

我建議只在兩種情況下使用any

  • 當你真正處理不可預知的類型的對象。即使這樣,您可能首先需要聲明一個interface類型來聲明合約(在運行時可能會或不會被實現)。

  • 當您將「ambient declarations」用於沒有相應的@types/* npm模塊的JavaScript庫時。這真是最後的選擇。好消息,環境聲明現在越來越不受歡迎。

+0

是否可以使用類而不是接口? – MiroO