打字稿变量类型说明

时间:2019-09-20 07:12:23

标签: typescript typescript-typings

在某些情况下,变量可以是 A B 。然后使用If我知道变量是什么类型,然后应用适当的响应。

我遇到TSLINT错误。

function checkIfItsAString(foo: String | Number): boolean {
  return foo instanceof String;
}

function example2(foo: String | Number) {
  if (checkIfItsAString(foo)) {
    foo.charAt(5);

    return;
  }
}

enter image description here

enter image description here

我该怎么说打字稿,

  

从现在开始,此变量的类型为“字符串”

2 个答案:

答案 0 :(得分:1)

您可以使用类型谓词使编译器自动缩小类型的范围。您的谓词已经有效,要使其成为类型谓词,您只需要说出它对值的含义:

function checkIfItsAString(foo: String | Number): foo is String {
//  tell the compiler true means it's a string -> ^^^^^^^^^^^^^
  return foo instanceof String;
}

这使编译器可以自动确定类型:

function example2(foo: String | Number) {
  if (checkIfItsAString(foo)) { //foo is a String

    foo.charAt(5);

    return;
  }

  foo.toFixed(""); //foo is a Number
}

Live demo on TypeScript Playground

或者,您可以直接使用in运算符,该运算符将从类型列表中进行类型消除:

function example2(foo: String | Number) {
  if ("charAt" in foo) {
  //   ^^^^^^ this only exists on String not on Number, so it's a String
    foo.charAt(5);

    return;
  }

  foo.toFixed(2); //a number, since it doesn't have "charAt"
}

Live demo on TypeScript Playground

这对于一次性更简单的检查更为有用,因此您不需要整个谓词来处理它。如果是用例,它可以用于缩小类型的范围。这是一个人为设计的示例,它使用in分几个步骤消除类型。

/* 
 * ake a Nnumber, String, array of Numbers, or the HTMLCollection array-like:
 * for Number - the value
 * for HTMLCollection - the length
 * for array of number - the sum + the length
 * for string - the length + the trimmed length
 */
function dummyExample(x : Number | String | Number[] | HTMLCollection) : number {
  if ("length" in x) { // String | Number[] | HTMLCollection
    let totalLength: number = x.length;

    if ("slice" in x) { // String | Number[]
      if ("reduce" in x) { // Number[]
        return x.reduce((a: number, b: Number) => a + b.valueOf(), 0) + length;
      } else { // String
        return x.trim().length + totalLength;
      }
    } else { // HTMLCollection
      return totalLength;
    }
  } else { // Number
    return x.valueOf();
  }
}

Live demo on TypeScript Playground

答案 1 :(得分:1)

编译器无法从boolean的{​​{1}}返回类型中推断出任何有用的东西;该函数的 name 告诉其他代码的读者您所期望的内容,但这完全没有帮助编译器。

相反,您需要明确指出这是type predicate,即通知编译器它可以使用它来根据结果缩小变量的类型。不仅会返回checkIfItsAString,还会返回boolean

foo is String

实际的实现无需更改,这只是编译器的额外信息。