2017-06-15 56 views
2

我很難過。下面的代碼打字稿失敗,這個錯誤編譯:在AccountScript中,Account是保留字嗎?

fails.ts(10,7): error TS2420: Class 'Account' incorrectly implements interface 'IAccount'. 
    Property 'name' is optional in type 'Account' but required in type 'IAccount'. 
fails.ts(11,3): error TS2403: Subsequent variable declarations must have the same type. Variable 'id' must be of type 'string', but here has type 'number'. 
fails.ts(11,3): error TS2687: All declarations of 'id' must have identical modifiers. 
fails.ts(14,3): error TS2687: All declarations of 'name' must have identical modifiers. 

但如果我重命名class Accountclass Hello它不會失敗。我瘋了嗎?其他人看到相同的行爲?

interface IObject { 
    id: number; 
    table_name: string; 
}; 

interface IAccount extends IObject { 
    user_id: number; 
    name: string; 
}; 
class Account implements IAccount { 
    id: number; 
    table_name: string = 'account'; 
    user_id: number; 
    name: string; 
}; 

我使用打字稿^ 2.3.4

這裏有失敗和非故障代碼的完整例子:https://gist.github.com/iffy/9d518d78d6ead2fe1fbc9b0a4ba1a31d

回答

3

名稱Account是不是保留字,但它是defined as part of lib.d.ts

///////////////////////////// 
/// IE DOM APIs 
///////////////////////////// 

interface Account { 
    rpDisplayName?: string; 
    displayName?: string; 
    id?: string; 
    name?: string; 
    imageURL?: string; 
} 

打字稿您Account和上執行declaration merging e在lib.d.ts並且導致您遇到的問題。如果您將文件轉換爲模塊,則Account將專用於您的模塊,TypeScript將停止嘗試將其與全局模塊組合。

例如,通過增加export {};你可以平凡把你的文件轉換成一個模塊:

interface IObject { 
    id: number; 
    table_name: string; 
}; 

interface IAccount extends IObject { 
    user_id: number; 
    name: string; 
}; 
class Account implements IAccount { 
    id: number; 
    table_name: string = 'account'; 
    user_id: number; 
    name: string; 
}; 

export {}; 
+0

哇...謝謝。 – iffy

+1

不客氣。我以前一直被這個咬傷。在我的情況下,它是'Element'或'Node'。 – Louis