[英]How to define a function that checks if the parameter is string in TypeScript 2.0
Say I have a function that checks if a parameter is string defined like this : 说我有一个函数,检查是否参数是这样定义的字符串:
function isString(value: any): boolean {
return typeof value === 'string' || value instanceof String;
}
Now when I use this function with typescript 2.0 control flow analysis I would expect the following to work : 现在,当我将此功能与Typescript 2.0控制流分析一起使用时,我期望以下工作正常:
function foo(param: string|Foo) {
if(isString(param)) {
// param is not narrowed to string here
} else {
// param is not narrowed to Foo here
}
}
Is there a different way I could define isString that would make the example if statement narrow the type of param correctly ? 我可以通过其他方式定义isString来使if语句正确缩小参数类型的示例吗?
Typescript has Type Guards to help with this. Typescript具有Type Guard来帮助解决此问题。
You can have a user defined guard : 您可以具有用户定义的警卫 :
function isString(value: any): value is string {
return typeof value === 'string' || value instanceof String;
}
function foo(param: string | Foo) {
if (isString(param)) {
// param is string
} else {
// param is Foo
}
}
But in your case you can just use typeof
: 但是在您的情况下,您可以只使用typeof
:
function foo(param: string | Foo) {
if (typeof param === "string") {
// param is string
} else {
// param is Foo
}
}
If Foo
is a class then you can also use instanceof
: 如果Foo
是一个类,那么您也可以使用instanceof
:
function foo(param: string | Foo) {
if (param instanceof Foo) {
// param is Foo
} else {
// param is string
}
}
The return type needs to use the custom type guard syntax for this to work: 返回类型需要使用自定义类型保护语法才能起作用:
function isString(value: any): value is string {
return typeof value === 'string' || value instanceof String;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.