S
S
sanex33392015-08-17 17:22:25
JavaScript
sanex3339, 2015-08-17 17:22:25

Typescript: why does an error occur when trying to access an element of an object that is described by an interface?

There is a type code

interface Interface {
  [id: string]: Interface2;
}

interface Interface2 {
  [id: string]: string|boolean;
}

var a:Interface = {
  abc: {
    a: 'a',
    b: 'b',
    c: 'c'
  },
  cde: {
    c: 'c',
    d: 'd',
    e: true
  }
};

if (a.cde.e) {
  console.log(1);
} else {
  console.log(2);
}

if (a['cde']['e']) {
  console.log(1);
} else {
  console.log(2);
}

In the code below you can see 2 conditions: in the 1st condition the compiler swears
Property 'cde' does not exist on type 'Interface'.
In the second condition - no.
Why does he swear in the 1st condition? How to make it so that it would not swear?
You can check here www.typescriptlang.org/Playground

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mak Alexey, 2015-08-18
@sanex3339

https://github.com/Microsoft/TypeScript/issues/4345 stigma "By Design"
At least it checks the type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question