What is the type of an object literal key as defined in TypeScript?

1.8k views Asked by At

I'm not using TypeScript as the primary language for this application, but as the type-hinting assist for JetBrains' WebStorm alongside JSDocs. I'm also using the keyMirror utility to create quasi-enum object literals.

Given the following:

//enums.js
var keyMirror = require('keyMirror');
module.exports = {
    CRUDVerbs: keyMirror({ //keymirror mirrors the key to value in objects
        CREATE: null,
        READ: null,
        UPDATE: null,
        DESTROY: null
    }
}

//app.js
var enums = require('enums.js');
var CrudTypes = enums.CRUDVerbs;
/** @type {??????????} **/
var returnedVal = functionFromElsewhere();
if(returnedVal === CrudTypes.CREATE) {
//code
} //..etc...

What is the type of returnedVal and of CrudTypes.CREATE, for the purposes of defining it in e.g. enums.d.ts?

1

There are 1 answers

1
David Sherret On BEST ANSWER

The code for keyMirror assigns the property key to the value:

for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        ret[key] = key;
    }
}

Therefore, the type of returnVal and CrudTypes.CREATE should be string.

Note that Object.keys(...) returns string[] in TypeScript and that the following code outputs string for all the keys:

var obj = { 1: null, "2": null };
for (var key in obj) {
    console.log(typeof key);
}