3

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......

1
  • If you declare it as ObjectInterface then you lose the type-safety. I don't know what you expected. Typescript is duck-typed so as long as your object conforms to the interface it'll be considered an implementation of the interface. Commented Nov 3, 2020 at 14:31

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hm I guess it still works not perfectly. When we change obj.wqwewqe.toFixed() to for example const x = obj.wqwewqe; there is no error...
obj.wqwewqe type is number | undefined, so it's normal that console.log(obj.wqwewqe) doesn't return any error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.