Home > Mobile >  How to get all keys that include dash?
How to get all keys that include dash?

Time:06-01

I am trying to workaround a deficiency in yargs library where types for configuration are produced both as kamelCase and kebab-case, e.g.

const argv = yargs
  .env('CAS')
  .help()
  .options({
    'app-path': {
      demand: true,
      type: 'string',
    },
  })
  .parseSync();

export type Configuration = typeof argv;

Now Configuration is {'app-path': string, appPath: string}.

I want to Omit dash-containing keys. However, how do I Pick all keys that contain a dash in the first place?

CodePudding user response:

Template literal types to the rescue:

type A = { 'app-path': string, appPath: string }

type B = Omit<A, `${string}-${string}`>;

Playground Link

CodePudding user response:

You can iterate the keys of the Configuration object and use a filter.

const keysToOmit = Object.keys(configObject).filter(s => Boolean(s.match(/-/)))

// keysToOmit: ['app-path']

Then you can iterate through the keys and omit them from the object.

keysToOmit.forEach(key => delete configObject[key])

// configObject: {appPath: 'string'}

Probably it's also wise to first clone the object before modifying it. Especially if you expect objects to be treated as immutable in your application.

  • Related