如何根据可选对象参数更改返回类型

huangapple go评论65阅读模式
英文:

How to change return type based on optional object parameter

问题

Sure, here's the translation of the code part you provided:

如何仅在obj参数中存在aX时创建{ a: boolean }

type IObjFunc = () => void

interface IObj {
    aX?: IObjFunc
    bX?: IObjFunc
    cX?: IObjFunc
}

interface IReturnData {
    a?: boolean
    b?: boolean
    c?: boolean
}

const func = (obj: IObj) => {
    const returnData: IReturnData = {}

    if (obj.aX)
        returnData.a = true
    
    if (obj.bX)
        returnData.b = true
    
    if (obj.cX)
        returnData.c = true

    return returnData
}

const test1 = func({ aX: () => undefined })

console.log(test1.a) // 通过
console.log(test1.b) // 无错误,应该出错

Playground

英文:

How to create { a: boolean } only if aX exist in the obj parameter

type IObjFunc = () => void

interface IObj {
    aX?: IObjFunc
    bX?: IObjFunc
    cX?: IObjFunc
}

interface IReturnData {
    a?: boolean
    b?: boolean
    c?: boolean
}

const func = (obj: IObj) => {
    const returnData: IReturnData = {}

    if (obj.aX)
        returnData.a = true
    
    if (obj.bX)
        returnData.b = true
    
    if (obj.cX)
        returnData.c = true

    return returnData
}

const test1 = func({ aX: () => undefined })

console.log(test1.a) // Pass
console.log(test1.b) // No error, should be error

Playground

答案1

得分: 1

将你的IReturnData修改为泛型,如果输入如下所示:

type IReturnData<T extends IObj> = {
    [K in keyof T
      as K extends `${infer P}X` ? P // 或者你选择的另一个映射表达式,如 `ReturnMapping[K]`
      : never
    ]-?: boolean;
} & unknown // <- 使泛型立即展开

并将你的函数修改为泛型形式:

const func = <T extends IObj>(obj: T): IReturnData<T> => {...}

Playground: https://tsplay.dev/mLvOAw

英文:

Modify your IReturnData to be generic if input

type IReturnData&lt;T extends IObj&gt; = {
    [K in keyof T
      as K extends `${infer P}X` ? P // or another mapping expression of your choice, like `ReturnMapping[K]`
      : never
    ]-?: boolean;
} &amp; unknown // &lt;- makes generic unwrap immediately

and make your function generic as

const func = &lt;T extends IObj&gt;(obj: T): IReturnData&lt;T&gt; =&gt; {...}

Playground: https://tsplay.dev/mLvOAw

huangapple
  • 本文由 发表于 2023年5月24日 19:23:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76323004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定