输入“ T | undefined”时,可以返回“ T”类型吗?

时间:2019-07-26 13:30:36

标签: typescript

在以下代码中,sureReturn应返回具体类型为T(在示例中为string)。相反,我得到string | undefined

是否可以肯定地返回非undefined类型?

interface Things {
    a?: string
}

const things: Things = {
    a: 'Hi'
}

function sureReturn<T>(val: T): T {
    if (val === undefined) {
        throw new Error('Nothing')
    }
    return val
}

const thing = sureReturn(things.a) // string | undefined - should only be string

https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgCoAtQHMDOyDeAUMicnAPwBcyOYU2hAvoYQgPYi3JiYi7UZseALwFipONQDkACWBSmLGAFcQCMMA41lUCACUIYHSAA8qAHwAKAG5wANgICUAsaWTAYyG-eTC-yVQATCBhQCEDHVzdSHig2AHdkEAhEgFEoOKhLKQA5Nh5sKUdxEmY3XSMoEGRbO0VWDi4Cvl9tXQNKkEtm3AA6OEiAekGaOmxkAB8AkGDQ5MDkAFoadDZlOwWOOwBPZAAjFFp6PiA

1 个答案:

答案 0 :(得分:3)

您可以将| undefined添加到val中的sureReturn中。即使传入T,也会使编译器将string推断为string | undefined

const myVar = ''

function maybeReturn(val?: string) {
    return val
}

function sureReturn<T>(val: T | undefined): T {
    if (!val) {
        throw new Error('Nothing')
    }
    return val
}

const thing = sureReturn(maybeReturn(myVar)) // string

另一种选择是使用条件类型(Exclude可以做到),但是第一种选择是可取的,条件类型会在实现中引起问题:

function sureReturn<T>(val: T): Exclude<T, undefined> {
    if (!val) {
        throw new Error('Nothing')
    }
    return val as Exclude<T, undefined> // assertion needed
}

const thing = sureReturn(maybeReturn(myVar)) // string