I have an object inside a large project that uses null as a key and that cannot be changed, since it would break things all over the app.
However, I’m getting Type null cannot be used as an index type. ts(2538)
all over the place. Is there a way to tell TypeScript to accept null as an object key the same way it accepts numbers as keys?
3
Answers
In TypeScript, when using an object as an index type, the type system enforces that the index must be assignable to
string
ornumber
. That’s why you’re getting the errorType null cannot be used as an index type
.Unfortunately, there is no way to directly tell TypeScript to accept
null
as a valid index type without modifying the TypeScript compiler or changing the definition of the object.However, if modifying the object is not an option, you can work around this issue by using a type assertion (
as
) to override the type checking temporarily. Here’s an example:By using
key as keyof typeof MyObject
, you’re essentially telling TypeScript to treatkey
as a valid key of theMyObject
object. However, keep in mind that this bypasses type checking, so you need to ensure thatkey
is a valid key at runtime; otherwise, you may encounter a runtime error.All keys in javascript are converted to strings or symbols. Even if assigned non string values, the keys are converted to string.
So
MyObject[null]
should become something likeMyObject['null']
and should work as is. All you have to do is use ‘null’ (as a string) instead ofnull
when accessing the property.Note that there is another change required. The below statement means that
key
can be assgined anystring
value or the valuenull
.But
MyObject
only has three valid keysa,b,null
. So you should modify your statement like:or
So,
key
can only be assigned validMyObject
keys.Playground
So, in TypeScript they actively decided to only allow the string or number type as index signatures. Probably because most of the time, anyone trying to index into an object using something like null is indicative of an error.
In your case, you can do something like this:
Hope that helps! Good luck.