如何在typescript getter函数中处理referenceError

时间:2018-05-27 13:23:53

标签: typescript typescript-typings

在打字稿中,我有一个带有数据库对象的项目,该对象是数组 电影院对象。我还有一个 throwif 函数。以下代码不会产生任何错误:

function throwIf(condition: boolean, message: string){
    if (condition) return new Error (message)
}

function getCinema(cineId: number, database: Database): Cinema {
    throwIf(cineId == null, 'cineId should not be null')
    throwIf(database == null, 'database should not be null')

    let cinema = database
        .find(cinema => cinema.id === cineId)

    if (!cinema) throw new Error (`No cinema with id : ${cineId} `)
    return cinema
}

但我宁愿这样写:

function throwIf(condition: boolean, message: string){
    if (condition) return new Error (message)
}

function getCinema(cineId: number, database: Database): Cinema {
    throwIf(cineId == null, 'cineId should not be null')
    throwIf(database == null, 'database should not be null')

    let cinema = database
        .find(cinema => cinema.id === cineId)

    throwIf(!cinema,`No cinema with id : ${cineId} `)
    return cinema
}

但它会抛出编译器错误:

Type 'Cinema | undefined' is not assignable to type 'Cinema'.
  Type 'undefined' is not assignable to type 'Cinema'.

有什么方法可以让它发挥作用吗? 没有键入返回值为Cinema | undefined?

1 个答案:

答案 0 :(得分:0)

if充当type guard

user type guard在类似情况下有用,但在此处不适用,因为它应该返回一个值并与if一起使用。

编译器无法静态分析像throwIf这样的函数作为类型保护。有open issue显示Node.js assert作为此限制的示例。

可以通过非空断言来解决这个问题:

...
throwIf(!cinema,`No cinema with id : ${cineId} `)
return cinema!;

由于throwIf之后需要始终如一地使用非空断言:

throwIf(!cinema,`No cinema with id : ${cineId} `)'
console.log(cinema!);
return cinema!;

或者使用no-op重新分配变量:

throwIf(!cinema,`No cinema with id : ${cineId} `)'
cinema = cinema!;
console.log(cinema);
return cinema;

或事先断言(在throwIf来电之前可以以负面方式影响类型a):

let cinema = database.find(cinema => cinema.id === cineId)!;
当前状态下的

throwIf在TypeScript中不能被认为是实用的;它并不比相应的if (...) throw ...语句短得多或更易读。