2015-11-20 43 views
2

我有困難想明白這一點:打字稿接口陣列類型錯誤TS2411

There are two types of supported index types: string and number. It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type. In this example, the property does not match the more general index, and the type-checker gives an error:

interface Dictionary { 
    [index: string]: string; 
    length: number; // error, the type of 'length' is not a subtype of the indexer 
} 

來源:TypeScript Handbook's interface

我已經試過4例,但仍不能明白髮生了什麼。任何人都可以解釋爲什麼只有[index: string]: string;將有錯誤TS2411? enter image description here

另一種情況:

another case

+0

你錯過了一個'codio @ compact-guide'。我看不出有什麼理由把它反正隱藏起來 – basarat

+0

想念兩個...... –

+0

不錯。隱藏它使我想了解更多:) – basarat

回答

0

,如果你有[index: string]: string;所有屬性必須是string。因此:

interface Dictionary { 
    [index: string]: string; 
    length: number; // error, length is not a string. 
} 
+0

謝謝,我很抱歉的回覆。我太愚蠢了。我在你的答案中再加入一個測試用例,你會幫助我嗎? –

+0

對不起,但我不清楚哪個代碼示例,您有一個關於 – basarat

+0

的問題,很抱歉,我只是添加它。 –

0

It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

還沒有問號,答案是不。這陣以任何方式不會工作:

interface Dictionary { 
    [index: string]: string; 
    length: number; // error 
} 

,因爲即使這將工作:

interface Dictionary { 
    [index: string]: string; 
} 

var dic: Dictionary = {} 
dic[1] = "123" 

請注意,我們使用數字爲字符串數組建立索引。

interface Dictionary { [index: string]: MYCLASS; }的目的是支持您定義允許的值,而不是指數的類型,對不起

你在做什麼是不是的接口,但數組:http://www.typescriptlang.org/Handbook#interfaces-array-types

0

與打字稿2.4的一種解決方法是

interface Dictionary { 
    [index: string]: string | number; 
    length: number; 
} 

但是,您可能需要顯式轉換使用

let v = dict.key as string