gpt4 book ai didi

javascript - 将接口(interface)属性声明为 bool 值或为多页表单返回 bool 值的函数

转载 作者:行者123 更新时间:2023-12-03 04:47:48 26 4
gpt4 key购买 nike

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

所以我想声明一个将在编程 API 中使用的接口(interface)来定义页面:

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})

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

@Component()
export class ParentControl {

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

...然后,当然:

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

但是编译器提示:

Types of property 'visible' are incompatible. Type '() => boolean' is not assignable to type 'boolean'.

是的,我完全明白。我不明白的是如何实现我想要实现的目标?

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

如何实现将接口(interface)属性设置为返回 bool 值的函数的目标?

最佳答案

类似于:

visible: boolean | () => boolean;

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

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

if (typeof props.visible === "function") {
visible = props.visible();
} else {
visible = props.visible;
}
}
<小时/>

编辑

可见:boolean | () => boolean 对于编译器来说没问题,你可以这样做:

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

( code in playground )

或者:

visible: boolean | (() => boolean)

关于javascript - 将接口(interface)属性声明为 bool 值或为多页表单返回 bool 值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42796560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com