首页 > 解决方案 > 打字稿变量类型规范

问题描述

我有一个变量可能是类型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;
  }
}

在此处输入图像描述

在此处输入图像描述

我怎么能对打字稿说,

从现在开始,这个变量的类型是“String”

标签: typescripttypescript-typings

解决方案


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

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
}

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"
}

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();
  }
}

TypeScript Playground 上的现场演示


推荐阅读