简体   繁体   English

Typescript - React,基于可选道具的条件回调道具类型

[英]Typescript - React, conditional callback prop type based on optional prop

I have a react component which accepts an optional prop isSingle (boolean) and a required prop onSelect (callback).我有一个反应组件,它接受一个可选的道具isSingle (布尔值)和一个必需的道具onSelect (回调)。

If isSingle prop is used, I need that my callback to have a different signature如果使用isSingle道具,我需要我的回调具有不同的签名

type IProps<T> = 
    {
        isSingle?: T;
    } & (
        T extends boolean ?
        { 
            onSelected: (option: string) => void; 
            isSingle: boolean;
        } : 
        { 
            onSelected: (option: string[]) => void; 
            isSingle: boolean;
        }
    );

I just wrote this and it works, but as you see I have to define multiple times isSingle prop, but also the complier assigns to it the following type (T | undefined) & boolean我刚刚写了这个并且它有效,但是正如你所见,我必须多次定义isSingle道具,而且编译器还为其分配了以下类型(T | undefined)和 boolean

How to properly implement this?如何正确实施?

Instead of a generic type, a discriminated union works better here:与泛型类型不同,有区别的联合在这里效果更好:

type IProps =
  | {
      isSingle?: false;
      onSelected: (option: string[]) => void;
    }
  | {
      isSingle: true;
      onSelected: (option: string) => void;
    };

You can combine this with additional props as well, like:您也可以将其与其他道具结合使用,例如:

type IProps = {
  commonProp: string;
} & (
  | {
      isSingle?: false;
      onSelected: (option: string[]) => void;
    }
  | {
      isSingle: true;
      onSelected: (option: string) => void;
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM