【问题标题】:Polymorphic React component has incorrect type inferences in IDE多态 React 组件在 IDE 中的类型推断不正确
【发布时间】:2022-01-26 03:52:00
【问题描述】:
declare const MyComponent = <A extends {id: bigint|number}>(props: MyProps<A>) => React.FC<{}>

interface MyProps<A extends {id: number}> {
  data: A[]
  orderBy: keyof A
}

declare const x: { id: number, foo: string }[]

const Foo = () => {
  <MyComponent data={x} orderBy="foo"/> // <-- Type 'keyof A' is not assignable to type 'never'
}

我认为这是因为 TS 无法从 data 推断出该类型是 { id: number, ... } 类型,因此它认为 data{} 类型,因此 keyof Anever 类型(所以orderBy 根本不可能是任何东西。

所以我的问题是,除了上面的// @ts-ignore 之外,我该如何解决这个问题?我可以在我的 TSX 中以某种方式手动指定 A 的类型吗?我什么都做不了

import { MyComponent } from ...
declare const specify = <A>() => typeof MyComponent<A> // <-- error here because of the <A> part after MyComponent

const Foo = <A ...>() => {
  const SpecialMyComponent = specify<A>()
  return <SpecialMyComponent .../>
}

如果 TS 认为它是 TSX 而不是指定泛型的值,您似乎无法在 TSX 中执行这些泛型。

【问题讨论】:

    标签: reactjs typescript tsx


    【解决方案1】:

    我在下面的代码中提供了解释性 cmets。如果有不清楚的地方,请随时回复:

    TS Playground

    import {default as React} from 'react';
    
    // bigint was missing from this union in MyProps:
    type ID = {
      id: bigint | number;
    };
    
    type MyProps <A extends ID> = {
      data: A[];
      orderBy: keyof A;
    };
    
    // Suggestion: use React.ReactElement if you're rendering JSX or a component that does:
    declare function MyComponent <A extends ID>(props: MyProps<A>): React.ReactElement;
    
    declare const x: { id: number; foo: string; }[];
    
    const Foo = () => {
      <MyComponent data={x} orderBy="foo"/> // ok
    }
    
    
    // And, finally... yes, you CAN use generics with TSX!
    
    type Y = { id: bigint; baz: string[]; };
    declare const y: Y[];
    
    const Bar = () => {
      <MyComponent<Y> data={y} orderBy="baz" /> // ok
    };
    

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 2021-03-03
      • 2021-02-11
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2018-03-16
      相关资源
      最近更新 更多