Typescript 当输入“时”;T“未定义”;您能返回一种“类型”吗;T";?

Typescript 当输入“时”;T“未定义”;您能返回一种“类型”吗;T";?,typescript,Typescript,在下面的代码中,sureReturn应返回具体类型的T(string)。相反,我得到的是string |未定义的 是否有方法明确返回非未定义的类型 interface Things { a?: string } const things: Things = { a: 'Hi' } function sureReturn<T>(val: T): T { if (val === undefined) { throw new Error('Not

在下面的代码中,
sureReturn
应返回具体类型的
T
string
)。相反,我得到的是
string |未定义的

是否有方法明确返回非
未定义的
类型

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
接口事物{
a:字符串
}
常数事物:事物={
a:你好
}
函数sureReturn(val:T):T{
如果(val==未定义){
抛出新错误('Nothing')
}
返回值
}
const thing=sureReturn(things.a)//string |未定义-应仅为string

您可以在
sureReturn
中将
未定义的
添加到
val
。这将使编译器推断
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

如何定义
maybeReturn
的返回类型?
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