2016-06-18 2 views

답변

10

인덱싱 가능 유형입니다. 이 변수 정의의 형태의 표현을 보면 :

let myIndexVar: { [key: string]: number; }; 
  • : { ... }는 객체 의미합니다.
  • [key: string]: number;은 개체의 색인 서명입니다. 인덱스 서명 내

:

  • [key: string]는 키 - key의 이름 - 그리고 키 - string의 유형을 정의합니다.
  • : number;은 값 유형이 number입니다.

이러한 유형과 같이 사용됩니다 : 당신이 키에게 당신이 원하는 이름을 지정할 수 있습니다

let myIndexVar: { [key: string]: number; } = {}; 

myIndexVar["key"] = 4; // key is string, value is number 

참고.

Intellisense example

+1

'key'는 임의의 문자열이 될 수 있습니다. 즉, myIndexVar [ "foobar"] = 37'도이 경우 유효한 할당이됩니다. –

0

가 더 Typscript docs

Indexable Types Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example:

interface StringArray { 
    [index: number]: string; 
} 

let myArray: StringArray; 
myArray = ["Bob", "Fred"]; 

let myStr: string = myArray[0]; 

Above, we have a StringArray interface that has an index signature. This index signature states that when a StringArray is indexed with a number, it will return a string.

There are two types of supported index signatures: string and number. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number) is the same thing as indexing with "100" (a string), so the two need to be consistent.

class Animal { 
    name: string; 
} 
class Dog extends Animal { 
    breed: string; 
} 

// Error: indexing with a 'string' will sometimes get you a Dog! 
interface NotOkay { 
    [x: number]: Animal; 
    [x: string]: Dog; 
} 

While string index signatures are a powerful way to describe the “dictionary” pattern, they also enforce that all properties match their return type. This is because a string index declares that obj.property is also available as obj["property"]. In the following example, name’s type does not match the string index’s type, and the type-checker gives an error:

interface NumberDictionary { 
    [index: string]: number; 
    length: number; // ok, length is a number 
    name: string;  // error, the type of 'name' is not a subtype of the indexer 
} 
에서 David Sherret

하여 답을 설명하기 위해 : 그것을 설명하는 이름을주는 것은 변수 이름도해야하지만 키는 것이 무엇인지 이야기하는 것이 도움이된다

관련 문제