[Typescript] Making TypeScript Stick - 6 - infer, build a ConstructorArg Type

For example we have a Webpack class:

class WebpackCompiler {
  constructor(options: {
    amd?: false | { [index: string]: any }
    bail?: boolean
    cache?:
      | boolean
      | {
          maxGenerations?: number
          type: "memory"
        }
    context?: string
    dependencies?: string[]
    devtool?: string | false
    entry?: string
    chunkLoading?: string | false
    dependOn?: string | string[]
    layer?: null | string
    runtime?: string
    wasmLoading?: string | false
    externalsType?:
      | "var"
      | "module"
      | "assign"
      | "this"
      | "window"
      | "self"
      | "global"
      | "commonjs"
      | "commonjs2"
      | "commonjs-module"
      | "amd"
      | "amd-require"
      | "umd"
      | "umd2"
      | "jsonp"
      | "system"
      | "promise"
      | "import"
      | "script"
 
    ignoreWarnings?: (
      | RegExp
      | {
          file?: RegExp
 
          message?: RegExp
 
          module?: RegExp
        }
    )[]
    loader?: { [index: string]: any }
    mode?: "development" | "production" | "none"
    name?: string
    parallelism?: number
    profile?: boolean
    recordsInputPath?: string | false
    recordsOutputPath?: string | false
    recordsPath?: string | false
    stats?:
      | boolean
      | "none"
      | "summary"
      | "errors-only"
      | "errors-warnings"
      | "minimal"
      | "normal"
      | "detailed"
      | "verbose"
    target?: string | false | string[]
    watch?: boolean
  }) {}
}

 

in our code, we made a spelling mistake:

const cfg = {
  entry: "src/index.ts",
  wutch: true, // SPELLING ERROR!!
}
try {
  const compiler = new WebpackCompiler(cfg)
} catch (err) {
  throw new Error(
    `Problem compiling with config\n${JSON.stringify(
      cfg,
      null,
      "  "
    )}`
  )
}

Typescript is not able to help us to find the bug, because everything in the consturct options type is optional.

 

So we want to build a ConstructorArg<C>to help us:

const cfg: ConstructorArg<typeof WebpackCompiler> = {
  entry: "src/index.ts",
  wutch: true, // SPELLING ERROR!!
}

 

type ConstructorArg<C> = C extends {
  new (arg: infer A, ...args: any[]): any
} ? A : never;

Try

 

Post

posted @ 2022-08-16 21:07  Zhentiw  阅读(14)  评论(0编辑  收藏  举报