首页 > 其他分享 >[Typescript] Making TypeScript Stick - 6 - infer, build a ConstructorArg Type

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

时间:2022-08-16 21:12:18浏览次数:91  
标签:index TypeScript false string cfg Typescript ConstructorArg boolean RegExp

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

标签:index,TypeScript,false,string,cfg,Typescript,ConstructorArg,boolean,RegExp
From: https://www.cnblogs.com/Answer1215/p/16592991.html

相关文章