Array type in type script

后端 未结 3 436
一个人的身影
一个人的身影 2021-01-14 03:11

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 StringA         


        
3条回答
  •  迷失自我
    2021-01-14 03:54

    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.

提交回复
热议问题