2016-08-22 172 views
2

根据使用对象字面值时的Typescript文档,它应该完全匹配接口。但对于下面的代码操场上不显示任何错误消息:Typescript编译器不显示错误

code pic from playground

下面支撑是字符串,因此它与[index: number]: number这意味着该指数应该是指数在数量和价值应该是一些冲突,属性除nameage以外。

这是一个错误?如果我错了,请解释这是如何工作的?

+2

请勿发布代码图片。 – 2016-08-22 13:03:47

+0

我发布它指出没有错误正在操场上显示。 –

+0

为游乐场示例生成链接非常简单。这样,试图回答您的问题的人可以快速检查代码。否则,只需在这里粘贴代码,那么审阅者就可以尝试编译它,这总是比图片更好的选择。 –

回答

1

您始终可以指定比接口要求更多的属性。作为示范,看看下面的代码:(or on the playground

// index.ts 
interface MyInterface { 
    obligatoryProperty: string 
    optionalProperty?: string 
    [index: number]: number 
} 

let impl1: MyInterface = {} // fails compilation 
let impl2: MyInterface = { obligatoryProperty: 'hello' } // compiles fine 
let impl3: MyInterface = { 
    obligatoryProperty: 'hello', 
    optionalProperty: 'hello', 
    2: 2, 
    3: 3, 
    notSpecifiedPropertyThatIsAlsoNotANumber: 'hello', 
} // Still fine