【发布时间】: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