Skip to content

Request: Optional strict typing on bracket access to properties #7733

@xi

Description

@xi

Tested with TypeScript 1.8.7

I have a situation where I need to access a property on an object with bracket notation because the property name contains dots. Unfortunately, TypeScript is less strict with the bracket notation:

interface IFoo {
  n: number;
  s: string;
}

function testNumber(x : number) {
  return x;
}

function (foo : IFoo) {
  testNumber(foo.n);  // pass
  testNumber(foo.s);  // fail
  testNumber(foo.asd);  // fail

  testNumber(foo['n']);  // pass
  testNumber(foo['s']);  // fail
  testNumber(foo['asd']);  // pass
}

foo.asd in this case fails because asd is not a valid property of IFoo. But foo['asd'] is assumed to be of type any.

I read somewhere that this behavior is intentional to offer some kind of backdoor. I am pretty sure I do not need that backdoor in my project, but I need foo['asd'] to fail. So it would be great if this behavior could be optionally turned on.

I guess the --noImplicitAny option would have some effect, but unfortunately turning it on would require major changes in the rest of my codebase, so that is not an option.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions