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

Typescript: Treating function parameter as a literal type

我正在尝试编写一个 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>
      )
    }
  }
}

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

的类型
P extends { [P in K ]: C }

P extends Record<K, C>