2015-11-20 8 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

Nice. Скрытие это заставило меня хотеть узнать больше :) – 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 
Смежные вопросы