打字稿:将函数参数视为文字类型

时间:2018-11-03 08:16:50

标签: reactjs typescript literals

我正在尝试编写一个HOC来使用React上下文,该上下文默认情况下只能与渲染道具一起使用。

它的工作方式是在上下文使用者中渲染WrappedComponent,并将上下文作为key道具传递,该道具在HOC使用期间提供。

该组件运行良好,并且生成的组件的类型正确,但是在实现中存在类型错误,因为K被用作键,但是在打字稿中,键必须是文字类型。有没有一种方法可以强制说泛型不仅是string而是字符串文字?

import React from "react"

function getConsumer<C>(
  Context: React.Context<C> | React.Consumer<C>,
): React.Consumer<C> {
  return (Context as any).Consumer || Context
}

export const withContext = <C extends any, K extends string>(
  Context: React.Context<C> | React.Consumer<C>,
  key: K,
) => <P extends { [K /* Error here, K must be a literal type */]: C }>(WrappedComponent: React.ComponentType<P>) => {
  type NewProps = Omit<P, K>

  return class WithContext extends React.Component<NewProps> {
    render() {
      const Consumer = getConsumer(Context)
      return (
        <Consumer>
          {context => (
            <WrappedComponent
              {...Object.assign({}, this.props, { [key || "context"]: context })}
            />
          )}
        </Consumer>
      )
    }
  }
}

1 个答案:

答案 0 :(得分:1)

无法强制K是文字类型,但是您可以使用映射类型而不是具有计算属性的类型

P extends { [P in K ]: C }

P extends Record<K, C>