gpt4 book ai didi

typescript - 我可以将 Typescript 函数参数定义为 bool 值或字符串类型吗?

转载 作者:行者123 更新时间:2023-12-02 01:03:56 30 4
gpt4 key购买 nike

我有这个功能:

network = (action: boolean): void => {
if (action) {
this.action = action;
this.net = true;
this.netd = true;
} else {
this.action = null;
this.net = false;
this.netd = false;
}
}

有没有一种方法可以让我在 typescript 中定义 Action 的值可以是 bool 值或字符串?

最佳答案

是的。只需使用 function 而不是 var:

function network(action:boolean):void;
function network(action:string):void;
function network(action: any): void {
if (action) {
this.action = action;
this.net = true;
this.netd = true;
} else {
this.action = null;
this.net = false;
this.netd = false;
}
}

network(''); //okay
network(true); // okay
network(12); // ERROR!

它称为函数重载,您也可以对成员函数执行此操作。

关于typescript - 我可以将 Typescript 函数参数定义为 bool 值或字符串类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24991006/

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