【问题标题】:Typescript pick from function argument打字稿从函数参数中挑选
【发布时间】:2019-07-27 19:44:41
【问题描述】:

在 TypeScript 中,下面的 useContext 是否可以从 Provider 中选择并返回值类型?

function Provider<Props = {value: number}>(props: Props) { }
function useContext<Value>(context: Context<Value>): Pick<Value, 'value'> { return 0 }

这样“Consumer”在使用时会返回type: number

function Consumer<Props>(props: Props) { return useContext(Provider) }

...有关其他上下文:

interface Component<Props = {}> { (props: Properties<Props>): Node }
interface Context<Value> extends Component<{value: Value}> {}

或者,给定

function Provider({value, children}: {value: string, children: any}) {
  return h(Context, {value: 'value'}, children)
}

const value = useContext(Provider)

假设函数“h”返回一个接口,如何将常量“值”归因于对象 {value: 'value'} 中的“值”:

interface {type: Context, props: {value: 'value}, children: children}

我尝试挑选,道具>,其中类型是“提供者”,然后从挑选的结果中挑选,道具>,'值'>。

然而这似乎不起作用。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    有一种很好的方法可以提取属性类型,称为“lookup types”(TypeScript 2.1 Notes)。 语法是:

    MyType['value'] // number
    

    其中MyType 包含属性value: number


    编辑:我无法按照您的示例进行操作,我尝试扩展 useContext's 'context' 参数并得到以下结果:

       function useContext<Value>(context: Context<Value>): Pick<Value, 'value'>;
    => function useContext<Value>(context: Component<{value: Value}>): Pick<Value, 'value'>
    => function useContext<Value>(context: (props: Properties<{value: Value}>) => Node): Pick<Value, 'value'>
    

    如果我们按照Value 类型进行第三次扩展,我们会看到没有约束;没有告诉编译器 Value 类型必须具有 'value' 属性。 Typescript 编译器根据 Value["value"]useContext(...) 返回类型的唯一方法是,如果有一些约束告诉编译器 'value' 存在于该类型上。

    一个选项,如果您将类型约束 &lt;Props extends {value: number} = {value: number}&gt; 添加到 ComponentProvider,编译器将能够推断出 props 具有 'value' 属性。

    另一个选项,使用keyof 并传入关键文字字符串(添加'key' 参数,并将返回类型更改为Pick&lt;Value, K&gt;)明确告诉编译器您已经知道哪个属性存在:

    function useContext<Value, K extends keyof Value>(context: Context<Value>, key: K): Pick<Value, K> {
      // ...
    }
    
    var value = useContext(Provider, 'value');
    

    【讨论】:

    • 我已经用更多上下文更新了这个问题。是的,我理解的查找类型在这种情况下不起作用,至少就我所尝试的而言。
    • 谢谢,查找类型是我所需要的,我对 Pick 在打字稿中的作用有错误的印象。
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多