[英]Type guards for function in TypeScript
I've defined a type Filter
in TypeScript, which can be string
, RegExp
or Predicator
, which is a function. 我已经在TypeScript中定义了类型Filter
,可以是string
, RegExp
或Predicator
,它是一个函数。 Type defines are listed below. 类型定义在下面列出。
export type Predicator = (input: string) => boolean;
export type SingleFilter = string | RegExp | Predicator;
There's a function taking SingleFilter
as input. 有一个函数以SingleFilter
作为输入。 However, the type guards seems to be not working with Predicator
, as long as RegExp
presists. 但是,只要RegExp
存在,类型保护程序似乎就不能与Predicator
一起使用。 But the issue is gone if the type is string | Predicator
但是,如果类型为string | Predicator
string | Predicator
only. 仅string | Predicator
。
function singlePredicator(value: any) {
if (typeof value === 'string') {
// do something for string
}
else if (value instanceof RegExp) {
// do something
}
else {
// do something for function
// Error TS2349: Cannot invoke an expression whose type lacks a call signature.
value(foo);
}
}
Is there any solution to make it work in my case? 有什么解决方案可以使其适用于我的情况吗? Thanks. 谢谢。 I'm using tsc
1.5.3 我正在使用tsc
1.5.3
The first change in the example below is that I have typed the value
paramater as a SingleFilter
rather than `any. 以下示例中的第一个更改是,我将参数value
键入为SingleFilter
而不是`any。
The second change is the type assertion in the last else
statement to hint to the compiler that value
is a Predicator
. 第二个变化是最后else
语句中的类型断言,以提示编译器该value
Predicator
。
export type Predicator = (input: string) => boolean;
export type SingleFilter = string | RegExp | Predicator;
function singlePredicator(value: SingleFilter) {
if (typeof value === 'string') {
// do something for string
return value.charAt(0);
} else if (value instanceof RegExp) {
// do something
value.test("Something");
} else {
// do something for function
var foo = "SomeFoo";
value(foo);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.