1

I got an error in the following definition in typescript, may I know what is the problem?

interface Dictionary {
[index: string]: string;
length: number; 
}
1
  • Did you read the error? Commented Nov 10, 2015 at 3:43

2 Answers 2

1

In your Dictionary interface,

[index: string]: string;

is called a string index signature, and tells the compiler all properties of a Dictionary must be of type string. You would commonly use an index signature to avoid having an array of mixed types.

So then doing this is OK:

let d: Dictionary;
d["foo"] = "bar";

But this will give a compiler error:

let d: Dictionary;
d["foo"] = 1000;

You can define properties for Dictionary, as long as every property you define is of type string. For example, this is OK:

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

And will allow you to do this:

let d: Dictionary;
d.foo = "bar";

But in your case, you tried to define a property called length as a number after you already told the compiler that all properties would be of type string. That's why you got a compiler error.

Sign up to request clarification or add additional context in comments.

Comments

0

Please see the TypeScript documentation on array types. All properties must have the same return type so you can't declare length with a return type number on the interface.

To get the length of the array you could cast back to a generic array type:

    (<Array<any>>yourArray).length

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.