首页 > 解决方案 > 根据参数是否未定义,函数如何能够知道确切的返回值?

问题描述

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

解决方案


Typescript 是一个在编译时工作的编译器,因此它只能知道当时已知的东西。

您的要求是运行时要求,某些属性的值只有在运行时才能知道,因此不可能与 TS 做。


推荐阅读