首页 > 解决方案 > 扩展两个接口中的任何一个并添加一些属性的接口?

问题描述

Action应该有属性children和。size?variant?

Action也应该实现ButtonLink

我怎样才能做到这一点?

这是我最好的尝试

interface Button {
    action: () => void;
    href?: never;
}
interface Link {
    href: string;
    action?: never;
}

interface Action extends Button | Link {
    children: string;
    size?: 'large' | 'small';
    variant?: 'secondary';
}

错误:

[tslint] Forbidden bitwise operation

我真正的功能要求是我想创建一个类型或接口,它有一些道具加上actionor href,但不是两者都有actionand href

标签: typescript

解决方案


不幸的是,接口不能扩展联合类型。您可以改用交集类型:

interface Button {
    action: () => void;
    href?: never;
}
interface Link {
    href: string;
    action?: never;
}

type Action =  (Button | Link) & {
    children: string;
    size?: 'large' | 'small';
    variant?: 'secondary';
}

let a: Action = {
    href: "",
    children: "",
    size: "large"
}


let a2: Action = {
    action: () => { },
    children: "",
    size: "large"
}


let a3: Action = { // error
    href: ""
    action: () => { },
    children: "",
    size: "large"
}

推荐阅读