我可以从带有类型谓词的函数中返回`void`吗?

时间:2019-11-13 19:37:40

标签: typescript

在编写数据验证API时,我经常提供两个函数-一个函数返回boolean,另一个函数引发。通常,抛出的返回类型为void

interface MyType {
    numberField: number;
    stringField: string;
}

function isMyType(o: any): o is MyType {
    return typeof o === "object"
        && o !== null
        && typeof o.numberField === "number"
        && typeof o.stringField === "string";
}

function validateMyType(o: any): void {
    if (!isMyType(o)) {
        throw new Error("Invalid MyType object.")
    }
}

我想做的是使用类型谓词,以便同一块(或任何子块)中的所有后续代码都可以采用对象的类型。

const input: any = ...;
validateMyType(input);
// here I would like TypeScript to understand that input is a MyType

我可以这样做吗?

2 个答案:

答案 0 :(得分:2)

您可以使用TypeScript 3.7中的新断言函数来执行此操作。详细了解它们in the TypeScript handbook

以您的示例为例,您可以将validate函数的返回类型更改为asserts o is MyType。这样会在validate调用之后,将相同范围内的后续代码中的参数类型通知给类型系统。

答案 1 :(得分:0)

您正在寻找新的custom type assertion syntax

interface MyType {

  numberField: number;

  stringField: string;
}
function isValid(o: any): o is MyType {
  return typeof o === "object"
    && o !== null
    && typeof o.numberField === "number"
    && typeof o.stringField === "string";
}

function validate(o: any): asserts o is MyType{
  if (!isValid(o)) {
    throw new Error("Invalid MyType object.")
  }
}

declare var o: any;
validate(o)
o.numberField //ok
o.numberField2 //err

Play

相关问题