4

Why is this allowed by TypeScript? I specified a numeric index. Why can I use a string as an index? Visual studio doesn't report an error.

interface StringArray {
    [index: number]: string;

}

var a: StringArray;
a = { "key": "val" };
var b = a["key"];
1
  • 2
    well, it is still Javascript, so it is valid as on any object you can access the property values like that Commented Nov 10, 2015 at 8:52

3 Answers 3

4

Problem

It's because the compiler is still allowing implicit any types which can happen when accessing a property of an object by using an index:

// Example 1
let dictionary: { [index: number]: string };
let myStringTypedVar = dictionary[5];   // implicitly typed as "string"
let myAnyTypedVar = dictionary["prop"]; // implicitly typed as "any"

// Example 2
let myNumberTypedVar = 5;
let myAnyTypedVar = myNumberTypedVar["prop"]; // implicitly typed as "any"

Fix: Compile with --noImplictAny

If you compile your example with --noImplictAny then it will error:

tsc --noImplicitAny example.ts

Outputs:

example.ts(8,9): error TS7017: Index signature of object type implicitly has an 'any' type.

I would recommend always compiling with --noImplicitAny. In Visual Studio, you can turn on --noImplictAny by unchecking "Allow implicit 'any' types" in the project properties' typescript build tab:

Disable allow implicit any

Or by adding "noImplicitAny": "true" to compilerOptions in tsconfig.json.

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

Comments

2

An array is also an objects. So you can access the object properties.

var array = [];
array.push("One"); // array
array[1]= "Two"; // array
array['key'] = "Three";// object
array.key2 = "Four"; // object
var length = array.length; // Is 2 

Comments

1

A numeric index signature only defines the type for properties accessed through a numeric index. It does not restrict property access to only a numeric index.

From the TypeScript 1.5 specification:

Numeric index signatures, specified using index type number, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type T, all numerically named properties must have types that are assignable to T

But, I think you have a good point. It does seem like properties should not be accessed by a string index if you have only defined a numeric index signature.

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.