繁体   English   中英

如何使用 TypeScript 进行类型化元编程?

[英]How can I do typed metaprogramming with TypeScript?

我正在创建一个 function 接收多个键和值,并应返回具有这些键及其各自值的 object。 值类型应该与我调用 function 时传递的值相匹配。

目前,该代码有效,但类型不准确。

我尝试使用工厂方式,希望 typescript 可以为我推断出一些东西。

这是工厂的代码。 此外,这里还有一个游乐场

const maker = (subModules?: Record<string, unknown>) => {
  const add = <Name extends string, Q>(key: Name, value: Q) => {
    const obj = {[key]: value};
    return maker({
      ...subModules,
      ...obj
    })
  }
  const build = () => {
    return subModules
  }

  return {
    add,
    build
  }
}

const m2 = maker()
  .add('fn', ({a, b}: { a: number, b: number }) => a + b)
  .add('foo', 1)
  .add('bar', 'aaaa')
  .build()
// m2.foo -> 1
// m2.bar -> 'aaaa'
// m2.fn({a: 1, b: 2}) -> 3
m2

还有管道( 操场)的选项,也许这个可能更容易:


type I = <T extends any[]>(...obj: T) => { [P in T[number]['key']]:  T[number]['value'] }
const metaMaker: I = <T extends any[]>(...subModules: T) => {
  return subModules.reduce((acc, curr) => {
    const op = {[curr.key]: curr.value}
    return {
      ...acc,
      ...op
    }
  }, {}) as { [P in T[number]['key']]: T[number]['value'] }
}
const m = metaMaker(
  {key: 'fn', value: ({a, b}: { a: number, b: number }) => a + b},
  {key: 'foo', value: 1},
  {key: 'bar', value: 'aaaa'},
)
// m.foo -> 1 
// m.bar -> 'aaaa'
// m.fn({a: 1, b: 2}) -> 3
// m

类似于@yeahwhat 的解决方案,但是这个在build中添加了一些额外的东西。 由于您要返回许多记录的交集,因此它会很快变得混乱。 extends infer O位,将交叉点“折叠”为单一类型。

const maker = <Submodules extends Record<string, unknown> = {}>(subModules?: Submodules) => {
  const add = <Name extends string, Q>(key: Name, value: Q) => {
    const obj = {[key]: value};
    return maker<Submodules & Record<Name, Q>>({
      ...subModules,
      ...obj
    } as Submodules & Record<Name, Q>)
  }
  
  const build = () => {
    return subModules as Submodules extends infer O ? { [K in keyof O]: O[K] } : never;
  }

  return {
    add,
    build
  }
}

我也做了第二个选项:

type Narrow<T> =
    | (T extends infer U ? U : never)
    | Extract<T, number | string | boolean | bigint | symbol | null | undefined | []>
    | ([T] extends [[]] ? [] : { [K in keyof T]: Narrow<T[K]> });

const metaMaker = <T extends { key: string; value: any }[]>(...subModules: Narrow<T>) => {
  return (subModules as T).reduce((acc, curr) => {
    const op = {[curr.key]: curr.value}
    return {
      ...acc,
      ...op
    }
  }, {}) as { [P in T[number]['key']]: Extract<T[number], { key: P }>['value'] }
}

您与原始解决方案非常接近,但我使用了一种特殊类型来缩小给定输入的类型,而无需使用as const 您缺少的部分是Extract<T[number], { key: P }>获取该键的特定值。 在您为每个键提供所有值之前。

游乐场(包含两者)

您可以在T泛型中跟踪初始类型,并在每次添加新条目时将其与Record<Name, Q>组合,使用交集类型,如下所示( 游乐场):

const maker = <T extends Record<string, any>>(subModules?: T) => {
  
  const add = <Name extends string, Q>(key: Name, value: Q) => {
    const obj = {[key]: value} as Record<Name, Q>;
    return maker<T & Record<Name, Q>>({...subModules, ...obj} as T & Record<Name, Q>)
  }

  const build = () => {
    return subModules
  }

  return {
    add,
    build
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM