如何为只有一个数组作为第一个参数或元素的扩展

时间:2017-08-27 18:24:28

标签: typescript

webpack-merge

考虑此功能
smart(...configuration | [...configuration])

它只接受一个Configuration[]...args: Configuration[]并返回Configuration

这个功能有什么类型?

更新:

我想为webpack-merge做一些打字。

这就是我到目前为止......

declare module 'webpack-merge' {

  import { Configuration } from 'webpack'

  type StrategyType = 'prepend' | 'append' | 'replace'
  type StrategyMap = { [feild: string]: StrategyType }
  type ConfigurationFolder = (
    conf?: Configuration[], 
    ...args: Configuration[]) => Configuration

  export const merge: ConfigurationFolder
  export const multiple: ConfigurationFolder
  export const smart: ConfigurationFolder

  export const smartStrategy: (options: StrategyMap) => ConfigurationFolder
  export const unique: ConfigurationFolder

  export default merge
}

......但它没有按预期工作。

以下是测试:

import * as webpackMerge from 'webpack-merge'

const webpackConfig = webpackMerge.smartStrategy({ entry: 'replace' })(
    configs,
    baseConfig 
    # must fail here: only one `Configuration[]` as first param,
    # or only `Configuration, Configuration, Configuration, ....`
  )

UPDATE2

我想要的是什么:

class Configuration { }
type Func = (...configuration: Configuration[]) => Configuration;

// usage
const myFunc: Func = (...configuration: Configuration[]) => {
  return new Configuration();
}

const conf = new Configuration;
const confs = [conf];

const r1 = myFunc(confs); // right
const r2 = myFunc(conf); // right
const r3 = myFunc(conf, conf); // right

const f1 = myFunc(confs, confs); // must fail, cause can accept only one array
const f2 = myFunc(conf, confs); // must fail, cause or array, or spread
const f3 = myFunc(confs, conf); // must fail, same

Here is a playable version of what I want.

UPDATE3

spin-off

1 个答案:

答案 0 :(得分:3)

我们可以使用function overloading来描述一个......

的函数
  

可以接受一个且只有一个Configuration[]...args: Configuration[]并返回Configuration

这是宣言。

declare function smart(...configuration: Configuration[]): Configuration;
declare function smart(configuration: Configuration[]): Configuration;

这是an example of its usage

// in the module's *.d.ts declaration file...

declare class Configuration { 
  public context: any;
  public entry: any;
  public output: any;
}

declare function myFunc(...configuration: Configuration[]): Configuration;
declare function myFunc(configuration: Configuration[]): Configuration;

// in the module consumer's *.ts file...

const conf = new Configuration();
const confs = [conf];

const r1 = myFunc(confs); // right
const r2 = myFunc(conf); // right
const r3 = myFunc(conf, conf); // right

const f1 = myFunc(confs, confs); // must fail, cause can accept only one array
const f2 = myFunc(conf, confs); // must fail, cause or array, or spread
const f3 = myFunc(confs, conf); // must fail, same