gpt4 book ai didi

reactjs - Typescript 和 React : Failing type inference when using React. 组件和条件类型的 Prop

转载 作者:搜寻专家 更新时间:2023-10-30 20:53:02 24 4
gpt4 key购买 nike

在下面的设置中,我尝试为 onChange 函数中的值参数获取正确的推断类型。下面的设置给了我一个类型为 string | number 的值虽然我认为它应该是 string鉴于该值被分配了 string .

import * as React from 'react'

type NumberProps = {
decimals: number;
};

type StringProps = {};

type Props<T> = {
value: T;
onChange: (value: T) => void;
} & (T extends number ? NumberProps : StringProps);

class Y<T extends string | number> extends React.Component<Props<T>> {}

new Y({ value: 2.5, onChange:((value) => { /* value is inferred as string | number, but should be number */ })})

有两件事会使推论正确——但在其他方面当然是不正确的——但可能会给出错误的线索:

  1. 我可以删除这部分 Props 类型:& (T extends number ?
    NumberProps : StringProps);

  2. 我可以做到 Y派生自 React.Component 以外的东西,例如例如类 class X<T> { constructor(props: T) {} } .

我是不是在做/预期会出错,或者这是 Typescript 和/或 React 类型中的错误。

最佳答案

如果类型推断不成功,您可以自己显式指定类型参数的值:

new Y<string>({ value: 'test', onChange:((value) => { /* value is now a string */ })})

关于reactjs - Typescript 和 React : Failing type inference when using React. 组件和条件类型的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com