打字稿使参数可选

时间:2020-02-06 19:04:52

标签: typescript typescript-typings

这里是playground

我试图使参数成为可选参数,但仍使打字稿理解从函数返回的内容。

如果定义了param,则返回param的类型。否则-如果未提供参数,则函数将返回undefined。

const meh = <T>(initialData?: T): { data: T | undefined} => {
    if (initialData) {
        return { data: initialData }
    }

    return {
        data: undefined
    }
}

const res1: undefined = meh().data // is ok:

type ResType = {
    hello: string
}

const res2: ResType = meh<ResType>({ hello: 'hello'}).data.hello // TS error: Object is possibly undefined

这有道理。不过,我发现了conditional types,尽管我可以做类似

const meh = <T>(initialData?: T): { data: T ? T : undefined} => {

,但是会出现语法错误。

1 个答案:

答案 0 :(得分:1)

您可以使用函数重载吗?

function meh(): { data: undefined };
function meh<T>(initialData: T): { data: T };

function meh<T>(initialData?: T): any {
    if (initialData) {
        return { data: initialData }
    }

    return {
        data: undefined
    }
}

type ResType = {
    hello: string
}

const res1: ResType = meh<ResType>({ hello: 'hello'}).data
const res2: undefined = meh().data