英文:
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) // 无错误,应该出错
英文:
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
答案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<T extends IObj> = {
[K in keyof T
as K extends `${infer P}X` ? P // or another mapping expression of your choice, like `ReturnMapping[K]`
: never
]-?: boolean;
} & unknown // <- makes generic unwrap immediately
and make your function generic as
const func = <T extends IObj>(obj: T): IReturnData<T> => {...}
Playground: https://tsplay.dev/mLvOAw
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论