Typescript: Why error (about Indexable Types)

Created on 24 Nov 2016  路  3Comments  路  Source: microsoft/TypeScript



TypeScript Version: 2.1.1 / nightly (2.2.0-dev.201xxxxx)

Code

// A *self-contained* demonstration of the problem follows...

interface test{
   [index: number]:number;
   length: number;
}

 let abc:test;
 abc[1] = 213;
 console.log(abc[1]);

error tip

abc[1] = 213;
TypeError:Cannot set property '1' of undefined

Expected behavior:

Actual behavior:

Question

Most helpful comment

TypeScript should even tell you that you're using abc before you've assigned it.

image

All 3 comments

Typescript does not initialize the interface for you.
So after let abc: test; the variable is still undefined.
Try let abc: test = {length: 0};

TypeScript should even tell you that you're using abc before you've assigned it.

image

Thank those who helped me

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

weswigham picture weswigham  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments