如何在 TypeScript 2.0 中定义一个检查参数是否为字符串的函数

How to define a function that checks if the parameter is string in TypeScript 2.0

假设我有一个函数来检查参数是否是这样定义的字符串:

function isString(value: any): boolean {
    return typeof value === 'string' || value instanceof String;
}

现在,当我将此函数与 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 
   }
}

有没有其他方法可以定义 isString 来使示例 if 语句正确缩小参数类型?

return 类型需要使用自定义类型保护语法才能工作:

function isString(value: any): value is string {
    return typeof value === 'string' || value instanceof String;
}

Typescript 有 Type Guards 来帮助解决这个问题。

你可以有一个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
    }
}

但在你的情况下你可以只使用 typeof:

function foo(param: string | Foo) {
    if (typeof param === "string") {
        // param is string
    } else {
        // param is Foo
    }
}

如果 Foo 是 class 那么你也可以使用 instanceof:

function foo(param: string | Foo) {
    if (param instanceof Foo) {
        // param is Foo
    } else {
        // param is string
    }
}