将interface属性声明为布尔值或为多页面形式返回布尔值的函数

时间:2017-03-14 21:07:32

标签: javascript typescript

我正在设计多步骤表单控件;有点像一种标签控件。表单将包含多个单独的页面。其中一些页面可能会根据运行时条件出现和消失。例如,如果用户选中了标有“显示隐藏页面!”的复选框。在第2页上,然后第3页会神奇地出现。

所以我想要声明一个在编程API中用来定义页面内容的接口:

export interface MultiFormPage {
    id: string;  // unique id of this page
    title: string;  // title of this page
    fieldIds: Array<string>;  // fields in this page
    visible: boolean;  // non-visible tabs aren't shown in the page list
    enabled?: boolean;  // non-enabled pages can't be selected
    active?: boolean;   // only the active page is shown
};

visible属性是有问题的属性。如您所见,它被声明为boolean属性。它足够简单,可以静态和不完整地填充,如:myControl.addPage({..., visible: true})

但我想要的是传递一个可以在运行时评估的函数,以确定在任何给定时刻该页面应该是visible。类似的东西:

@Component()
export class ParentControl {

  iWasTriggered(): boolean {
    return this.formComponent.form['trigger'];
  }
};

......然后,当然:

myControl.addPage({..., visible: this.iWasTriggered});

但是编译器抱怨道:

  

属性“可见”的类型不兼容。           输入'()=&gt; boolean'不能赋值为'boolean'。

是的,我完全明白了。我没有得到的是如何实现我想要完成的目标?

我在代码中尝试了很多东西(例如将visible的声明更改为visible?: (): boolean;等),但我无法理解我需要的神奇咒语

如何实现将接口属性设置为返回布尔值的函数的目标?

1 个答案:

答案 0 :(得分:1)

类似的东西:

visible: boolean | () => boolean;

然后你需要使用一个类型保护来检查它是哪种类型:

addPage(props: MultiFormPage): void {
    let visible: boolean;

    if (typeof props.visible === "function") {
        visible = props.visible();
    } else {
        visible = props.visible;
    }
}

修改

由于编译器visible: boolean | () => boolean正常,你可以这样做:

type ReturnBoolean = () => boolean;
...
visible: string | ReturnBoolean;

code in playground

或者:

visible: boolean | (() => boolean)