如何获取所有包含破折号的键?

How to get all keys that include dash?

我正在尝试解决 deficiency in yargs library 配置类型同时作为 kamelCase 和 kebab-case 生成的问题,例如

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

export type Configuration = typeof argv;

现在 Configuration{'app-path': string, appPath: string}

我想省略包含破折号的键。但是,如何首先选择所有包含破折号的键?

您可以迭代 Configuration 对象的键并使用过滤器。

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

// keysToOmit: ['app-path']

然后您可以遍历键并从对象中省略它们。

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

// configObject: {appPath: 'string'}

在修改对象之前先克隆对象可能也是明智的。特别是如果您希望对象在您的应用程序中被视为不可变的。

Template literal types 救援:

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

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

Playground Link