2017-06-15 84 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