1

我有一个大的(2000 行)javascript 文件,我正在通过转换为 typescript 来实现,在我目前遇到的烦恼中,我看到了这样的模式:

var data = { some_property: some_value, another_property: some_other_value };

然后后来:

$.ajax({

...

complete: function(cfg) {
    var result = JSON.parse(cfg.responseText);
    data.some_property = result.some_property; // This is fine.
    data.some_different_property = result.some_different_property; // error
});

我收到一个错误,例如:“{some_property: ..., another_property: ... }”类型的值上不存在属性“some_different_property”。

虽然它从 var data = {...} 行中的值推断类型很酷,但在使用此模式的所有时间将所有潜在属性手写到数据中会相当痛苦,这是一个编译错误。

是否有一些编译器标志/方法可以让编译器推断这里的数据也有 some_different_property?:(从使用中推断出的类型)而不是堵塞我的错误列表?

4

2 回答 2

1

You can define an interface with optional parameters, and then specify that your variable matches that interface:

interface my_interface {
  some_property;    // type defaults to 'any'
  another_property: string;
  some_different_property?: number;
}
var data: my_interface = { some_property: 10, another_property: '' };
data.some_different_property = 99;

You can also do this inline, if this interface isn't reused:

var data2: { prop1; prop2; prop3? } = { prop1: 1, prop2: 2 };
data2.prop3 = "three";
于 2013-10-19T02:55:01.763 回答
1

No there isn't any compiler flag. However you can always type it to be any manually:

var data:any = { some_property: some_value, another_property: some_other_value };

Here you are telling the compiler that ignore what I am assigning to this variable, there can be other properties (potentially even called some_propertIE, i.e. the compiler cannot check any misspellings for you once you allow this).

Alternately you can split declaration / assignment to separate lines. In this case the type is inferred to be any by default. However making this your default pattern can result in effectively untyped code.

var data; // compiler infers it to by any 
data = { some_property: some_value, another_property: some_other_value }; // and you can assign anything
于 2013-10-17T23:34:17.273 回答