代码之家  ›  专栏  ›  技术社区  ›  Alyona

使用propTypes阻止道具

  •  0
  • Alyona  · 技术社区  · 4 年前

    我有一个按钮,可以有多个道具:

    interface buttonProps {
        secondary?: boolean;
        tertiary?: boolean;
        width?: number;
        children?: any;
        icon?: string;
    }
    

    如果按钮有 icon 没有通过 children ,我想防止添加道具: secondary , tertiary width 这可能与TypeScript有关吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   captain-yossarian from Ukraine    4 年前

    是的,有可能:

    更新

    type OnlyIcon = {
        icon: string;
    }
    type IconWithChildren = {
        secondary: boolean;
        tertiary: boolean;
        width: number;
        children: any;
        icon: string;
    }
    
    // credits goes to Titian Cernicova-Dragomir
    //https://stackoverflow.com/questions/65805600/struggling-with-building-a-type-in-ts#answer-65805753
    type UnionKeys<T> = T extends T ? keyof T : never;
    type StrictUnionHelper<T, TAll> =
        T extends any
        ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
    
    type StrictUnion<T> = StrictUnionHelper<T, T>
    
    type ButtonProps = StrictUnion<IconWithChildren | OnlyIcon>;
    
    const props: ButtonProps = {
        icon: 'd',
    } // ok
    
    const props2: ButtonProps = {
        icon: 'd',
        secondary: true
    } // error
    
    const props3: ButtonProps = {
        icon: 'd',
        secondary: true,
        tertiary:false,
    } // error
    
    const props4: ButtonProps = {
        icon: 'd',
        secondary: true,
        tertiary:false,
        width:1
    } // error
    
    const props5: ButtonProps = {
        icon: 'd',
        secondary: true,
        tertiary:false,
        width:1,
        children:{}
    } // ok
    

    Playground

    文件: Unions , Conditional types , DIstributive conditional types