【问题标题】:Typescript make param optional打字稿使参数可选
【发布时间】:2020-05-22 21:48:54
【问题描述】:

这里是playground

我正在尝试使参数成为可选参数,但仍然让 typescript 了解函数返回的内容。

如果定义了参数,则返回参数的类型。否则 - 如果没有提供参数,函数将返回 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 = &lt;T&gt;(initialData?: T): { data: T ? T : undefined} =&gt; {

,但它给出了语法错误。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案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
    

    【讨论】:

    • 我以前从未使用过它们。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2022-11-16
    • 2020-03-17
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多