简体   繁体   中英

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

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 eg enums.d.ts ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM