marcus-linmarkson
marcus-linmarkson

Reputation: 363

Typescript doesn't check object property existence when it is typed as [key: string]

I have typed my object of objects as:

export interface ObjectInterface {
  [key: string]: SomeOtherObjectInterface;
}

Then let's say I have object like:

const obj: ObjectInterface = {
   a: ...,
   b: ...,
}

Then when I want to access some object property it is not type-safe:

const x = obj.dsdssdsdsds;

There is no error within my IDE.

When I remove type from obj it throws an error properly. What could be done here to use our type but still get errors like Property 'dsds' does not exist on type......

Upvotes: 3

Views: 783

Answers (1)

KiraLT
KiraLT

Reputation: 2607

Typescript 4.1-beta has solved this issue.

These is a new option: --noUncheckedIndexedAccess.

Turning on noUncheckedIndexedAccess will add undefined to any un-declared field in the type.

You can test it on TypeScript playground.

Read more: Announcing TypeScript 4.1 Beta - Pedantic Index Signature Checks (--noUncheckedIndexedAccess)

By the way, the same issue is with arrays. If you access the array by index, you won't get any typescript error, even if that index doesn't exist. Fortunately, this option solves the array issue too.


P. S. 4.1 is released - read more about noUncheckedIndexedAccess

Upvotes: 2

Related Questions