简体   繁体   中英

Get TypeScript code completion on extended objects

I have a config file for my app conf.ts , which merges config values from other files, to keep it organized. I merge them, because when I want to use a config value, it is easier to write Conf.MY_LONG_NAMED_VALUE , than Conf.SubCategory.MY_LONG_NAMED_VALUE

import {CoreConf} from './conf/game/core.conf';
import {ViewConf} from './conf/view/view.conf';
import {DebugConf} from './conf/game/debug.conf';

/**
 *
 * @namespace Conf
 */
export const Conf: {[index: string] : any} = $.extend({},
    CoreConf,
    DebugConf,
    ViewConf
);

I am currently migrating from JavaScript to TypeScript, and while JavaScript code completion in WebStorm worked (because of the JSDoc tag @namespace ), TypeScript does not autocomplete the config names in the sub categories.

The two solutions I've found, is to either just use one file = one object, which is less organized, or create an index signature (or interface) with all config names, which is double the work.

Is there a better way to make this work?

You can type Conf to be an intersection type between your configs:

export const Conf: typeof CoreConf & typeof DebugConf & typeof ViewConf 

Or you could use Object.assign which is typed to return an intersection type of all parameter types

export const Conf = Object.assign({}, CoreConf, DebugConf, ViewConf)

While researching a different problem, I stumbled upon a third solution - spread syntax:

export const Conf = {...CoreConf, ...DebugConf, ...ViewConf}

For me this benefitted by forcing an Excess Property Check, which I wanted in another part of my code.

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