【问题标题】:Declare interface property to be a boolean or a function returning a boolean for a multi page form将接口属性声明为布尔值或为多页表单返回布尔值的函数
【发布时间】:2017-08-05 09:54:24
【问题描述】:

我正在设计多步表单控件;有点像一种选项卡式控件。该表格将由多个单独的页面组成。其中一些页面可能会根据运行时条件出现和消失。例如,如果用户选中了一个标记为“显示隐藏页面!”的复选框。在第 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});

但是编译器抱怨:

“可见”属性的类型不兼容。 类型 '() => boolean' 不可分配给类型 'boolean'。

是的,我完全明白。我没有得到的是我如何完成我想要完成的事情?

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

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

【问题讨论】:

    标签: javascript typescript


    【解决方案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 | () =&gt; boolean 对编译器没有问题,您可以这样做:

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

    (code in playground)

    或者:

    visible: boolean | (() => boolean)
    

    【讨论】:

    • +1: () =&gt; boolean 确实是我正在寻找的魔法咒语。然而,我的编译器对这种交替非常不满意 (boolean | () =&gt; boolean) 说它期待一个类型,我给它胡言乱语。这个 2014 年的随机链接说不是 2014 年语言的一部分。
    • 您提供的交替语法是否正确?它甚至合法吗?
    • 这是语言的一部分好吧,它被称为Union Types。编译器写了“gibber”?错误信息是什么?
    • 不,'gibber' 是我的翻译。它实际上是这样说的:
    • [at-loader] 检查完成,出现 3 个错误 [at-loader] src\app\components\ui\form\multiform.component.ts:15:31 TS1110: Type expected.
    猜你喜欢
    • 2015-05-23
    • 2018-01-24
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2013-03-11
    • 1970-01-01
    相关资源
    最近更新 更多