【问题标题】:How to handle referenceError in typescript getter function如何处理打字稿getter函数中的referenceError
【发布时间】:2018-05-27 13:23:52
【问题描述】:

在打字稿中,我有一个带有 Database 对象的项目,该对象是一个 array 电影 对象。我还有一个 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 ?

【问题讨论】:

  • 如果我理解正确,你想要这个:function getCinema(cineId: number, database: Database): any{.
  • @sr9yar 你永远不想any出现在任何可以避免的地方。
  • @estus,它违背了目的,我同意 :) 在我看来,这些函数中应该有完全不同的逻辑,否则......
  • @sr9yar 你会怎么做?我也可以更改它的整个逻辑,只是想找到带有 getter 的最佳解决方案和抛出错误的方法:)
  • 也许你应该从一开始就定义你的影院类型cinema: Cinema;,因为你的返回值必须是Cinema

标签: typescript typescript-typings


【解决方案1】:

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!;

或者重新分配一个没有操作的变量:

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 ... 语句更短或更易读。

【讨论】:

  • 谢谢@estus,这是我需要的信息;)
  • 很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2019-06-21
  • 2021-05-26
  • 1970-01-01
  • 2022-01-24
  • 2016-04-07
  • 2015-09-18
  • 2018-12-27
相关资源
最近更新 更多