【问题标题】:generic doen't check types between two property泛型不检查两个属性之间的类型
【发布时间】:2022-12-22 03:29:21
【问题描述】:
type ComponentType = (...args: any) => any;

type PlatformNotificationProps<TIcon extends ComponentType = ComponentType> = {
  component: TIcon;
  arg: Parameters<TIcon>[0];
};

const PlatformNotification = (props: PlatformNotificationProps) => {};

const Icon = (name: string) => '';

const result = PlatformNotification({
  component: Icon,
  arg: 100,
});

在这种情况下,或“arg”不正确,应该是一个字符串,或者组件不正确,应该接受数字而不是字符串。 我希望在控制台中看到错误,但一切正常。

我如何为这种情况编写类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用泛型时,链上的所有类型都需要传递泛型参数。

    由于您在 PlatformNotificationProps 中默认了参数,然后在不配置它的情况下使用该类型,TS 将不知道将您的函数的参数与泛型的参数相关联

    这是您可以通过使链中的所有元素都可配置来实现的一种方法

    type Fn<Args extends any[] = any[]> = (...args: Args) => any;
    
    type PlatformNotificationProps<Args extends any[], TIcon extends Fn<Args>> = {
      component: TIcon;
      arg: Parameters<TIcon>[0];
    };
    
    const PlatformNotification = <Args extends any[] = any[], Comp extends Fn<Args> = Fn<Args> >(props: PlatformNotificationProps<Args, Comp>) => {};
    
    const Icon = (name: string) => '';
    
    const result = PlatformNotification({
      component: Icon,
      arg: 100,
    });
    

    【讨论】:

      【解决方案2】:

      主要问题是您将默认泛型分配给PlatformNotificationProps

      type PlatformNotificationProps<TIcon extends ComponentType = ComponentType> = {
      ...
      

      当你在没有合适的泛型类型的情况下调用这个类型时,typescript 只能推断它是ComponentType,这就是为什么arg 可以接受数字,因为它实际上被键入为any

      const result = PlatformNotification({
        component: Icon,
        arg: 100,
      // ^? (property) arg: any
      });
      

      component 实际上也是一样的:

      const result = PlatformNotification({
        component: () => null, // no errors
        arg: 100,
      });
      

      为了解决这个问题,请使用以下类型调用PlatformNotificationProps

      const PlatformNotification = (props: PlatformNotificationProps<typeof Icon>) => {};
      

      现在:

      const result = PlatformNotification({
        component: Icon,
        arg: 100, // error: type `number` is not assignable to `string`
      });
      

      【讨论】:

        猜你喜欢
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        相关资源
        最近更新 更多