typescript - 根据参数是否未定义,函数如何能够知道确切的返回值?
问题描述
interface Activity {
eat: () => void
}
interface Person {
activity?: Activity
}
const activity = <T extends Person>(person: T) => ({
eat: person.activity && person.activity.eat
})
const tom = {
activity: {
eat: () => {}
}
}
const tomAct = activity(tom)
tomAct.eat() // should know `eat` does exist
const bobAct = activity({})
bobAct.eat // should know `eat` is undefined
您可以看到 tomAct.eat 将返回eat: (() => void) | undefined
,但tomAct
在这种情况下,知道eat: (() => void
并且 bobAct 是已知的undefined
。
Typescript 是否支持这种情况?我该如何解决?
===
“打字稿”:“^3.1.2”,
解决方案
Typescript 是一个在编译时工作的编译器,因此它只能知道当时已知的东西。
您的要求是运行时要求,某些属性的值只有在运行时才能知道,因此不可能与 TS 做。
推荐阅读
- javascript - How to wait on async .then
- spring-boot - 从 Spring Cloud Configuration 加载属性数组
- flutter - 由于 cloud_firestore,无法安装 permission_handler 和 file_picker
- r - plot.window(…) 中的错误:需要有限的“xlim”值,但看起来一切都很好
- python - 从 psycopg2 在 Postgres 中插入 dict 列表作为 json 数组
- python - 在 Heroku 中上传烧瓶应用程序并且工作正常但在我的终端中出现错误,(拉取函数中的错误)
- php - 从某个日期到 12 月计算月份,然后从次年 1 月到同年 12 月计算月份,然后从 1 月到结束日期
- git - 每当我们使用 dotnet 格式运行 git commit 时,如何格式化代码?
- javascript - 需要根据javascript中的特定要求修改数组
- rxjs - 如何在 Svelte 中使用 RXJs 主题之类的存储变量