TypeScript - Accessing object with null key

Objects in JavaScript is just a key value pair and key is usually string and value can be anything. The following is an example of JavaScript object literal

var car = {
    wheels : 3,
    colour: 'red',
    drive: function(){

The key in the object can be null. The default route in AngularJS is associated with null key, for example.

We can access the value associated with the null key in JavaScript quite easily like this:


If you do the same in TypeScript, you will get the following error

An index expression argument must be of type string, number, symbol, or any.

So, how do we make it work? It turns out that rather than using null key word, you can use a variable which is null. The following code is valid in TypeScript.

var nullRef: any = null;

I spent long time to get it working so posting this here for future reference.

comments powered by Disqus