使用 propTypes 防止道具

Prevent props using propTypes

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

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

如果按钮 icon 没有通过 children,我想阻止添加属性:secondarytertiarywidth。可以使用 TypeScript 吗?

是的,有可能:

更新

type OnlyIcon = {
    icon: string;
}
type IconWithChildren = {
    secondary: boolean;
    tertiary: boolean;
    width: number;
    children: any;
    icon: string;
}

// credits goes to Titian Cernicova-Dragomir
//
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