如何为回调函数或布尔值设置联合类型?我试过了,但是得到了:
export interface IActions {
dragend?: ((m:any)=>void) | boolean;
click?: ((m:any)=>void) | boolean;
dblclick?: ((m:any)=>void) | boolean;
}
// using the following type guard in code
// also tried `this.setting.click instanceof Function`
if (typeof this.setting.click != 'boolean'){
this.setting.click(m);
} else {
// default action
}
错误:
错误TS2349:无法调用类型缺少调用签名的表达式。输入'boolean | ((m:any)=> void)'没有兼容的呼叫签名。
答案 0 :(得分:1)
您可以使用type guards创建自动为您键入变量的if语句。
编写这些保护措施的一种方法是:
(原谅命名...我今天觉得自己没有创造力!)
type Action = (m: any) => void;
type ActionOrBoolean = Action | boolean;
function isActionOrBooleanAction(actionOrBoolean: ActionOrBoolean): actionOrBoolean is Action {
return typeof actionOrBoolean != 'boolean';
}
function isActionOrBooleanBoolean(actionOrBoolean: ActionOrBoolean): actionOrBoolean is boolean {
return typeof actionOrBoolean == 'boolean';
}
它们可以像这样使用:
let v3: ActionOrBoolean = (Math.random() > 0.5)
? (p1: any) => {}
: true;
if(isActionOrBooleanBoolean(v3)) {
v3 = false;
} else if(isActionOrBooleanAction(v3)) {
v3("");
}
最后,这是一个jsFiddle,显示一切正常。
writeLine("v1: " + v1);
writeLine("v1 isActionOrBooleanAction: " + isActionOrBooleanAction(v1));
writeLine("v1 isActionOrBooleanBoolean: " + isActionOrBooleanBoolean(v1));
writeLine("v2: " + v2);
writeLine("v2 isActionOrBooleanAction: " + isActionOrBooleanAction(v2));
writeLine("v2 isActionOrBooleanBoolean: " + isActionOrBooleanBoolean(v2));
// Example
let v3: ActionOrBoolean = (Math.random() > 0.5)
? (p1: any) => {}
: true;
if(isActionOrBooleanBoolean(v3)) {
v3 = false;
} else if(isActionOrBooleanAction(v3)) {
v3("");
}
输出:
v1:是
v1 isActionOrBooleanAction:false
v1 isActionOrBooleanBoolean:true
v2:函数(p1){}
v2 isActionOrBooleanAction:true
v2 isActionOrBooleanBoolean:false