打字稿类型检查对象文字的问题

时间:2014-08-21 14:47:33

标签: typescript object-literal

在TypeScript中,你经常有一个JS库的外部接口定义,其中许多(如果不是所有)字段都是可选的,通常是因为有很多字段,你不想强迫库的用户将它们全部填入。大多数字段都有合理的默认值。

因此,在声明界面时,您将字段标记为可选的?但是这严重限制了对象文字的类型检查,因为它现在不会捕获属性名称拼写错误。因为任何对象都实现了接口,所以具有额外属性的任何对象也恰好是实际属性的错字。

参见示例:

interface SomeExternalLibraryConfiguration {
    prop1 ? : number;  //Defaults to 0;  
    prop2 ? : string;  //Defaults to null
    prop3 ? : boolean; //Defaults to true
}

//This works fine
var conf1 : SomeExternalLibraryConfiguration = { prop1 : 10, prop2 : 'hello', prop3: false};

//So does this
var conf2 : SomeExternalLibraryConfiguration = { prop1 : 10};

//So does this, compiler flags the wrong type
var conf3 : SomeExternalLibraryConfiguration = { prop1 : '10'};

//But what about this?  No love from the compiler - how to I get the compiler to recognize the typo?
var conf4 : SomeExternalLibraryConfiguration = { prap1 : 10};

//Oddly though this is only a problem with object literals, as here the compiler does what I want and flags prap1
var conf5 : SomeExternalLibraryConfiguration;
conf5.prap1 = 10;

有没有办法告诉编译器“我希望这个对象文字能够实现这个接口,只有这个接口”?

1 个答案:

答案 0 :(得分:0)

  

我希望这个对象文字能够实现这个接口,并且只有这个接口

目前不是。听起来像https://github.com/microsoft/typescript/issues

的好功能请求