“帐户”是TypeScript中的保留字吗?

时间:2017-06-15 16:56:16

标签: typescript

我很难过。以下TypeScript代码无法使用此错误进行编译:

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 Account重命名为class 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;
};

我正在使用TypeScript ^ 2.3.4

这是一个包含失败和无失败代码的完整示例:https://gist.github.com/iffy/9d518d78d6ead2fe1fbc9b0a4ba1a31d

2 个答案:

答案 0 :(得分:5)

名称Account不是保留字,而是defined as part of lib.d.ts

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

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

TypeScript会在Account上执行declaration merging,在lib.d.ts中执行Boost Integer Library,这会导致您遇到问题。如果您将文件转换为模块,则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 {};

答案 1 :(得分:0)

Typescript保留字列表:

保留字:

以下关键字是保留关键字,不能用作标识符:

break             case              catch                 class  
const             continue          debugger              default  
delete            do                else                  enum  
export            extends           false                 finally  
for               function          if                    import  
in                instanceof        new                   null  
return            super             switch                this  
throw             true              try                   typeof  
var               void              while                 with

以下关键字不能在严格模式代码中用作标识符,但不受其他限制:

implements            interface         let                  package  
private               protected         public               static  
yield

以下关键字不能用作用户定义的类型名称,但不受其他限制:

any               boolean           number            string  
symbol

以下关键字在某些情况下具有特殊含义,但它们是有效的标识符:

abstract             as                    async                 await  
constructor          declare               from                  get  
is                   module                namespace             of  
require              set                   type