gpt4 book ai didi

typescript - 创建嵌套映射类型

转载 作者:行者123 更新时间:2023-12-05 03:37:05 25 4
gpt4 key购买 nike

我有两种类型:

type ContactPerson = {
firstName: string
lastName: string
}
type Customer = {
companyName: string
contactPerson: ContactPerson
}

我需要以通用方式将此类型映射到

type Result = {
companyName: boolean[]
contactPerson: {
firstName: boolean[]
lastName: boolean[]
}
}

我可以映射根级别,但如何处理嵌套属性?

type BooleanResult<T> = {
[Prop in keyof T]: boolean[]
}

最佳答案

我是这样解决的:

type BooleanResult<T> = {
[K in keyof T]: T[K] extends object ? BooleanResult<T[K]> : boolean[]
}

它按预期工作,但类型信息显示:

type Result = {
companyName: boolean[];
contactPerson: BooleanResult<{
firstName: string;
lastName: string;
email: string;
}>;
}

关于typescript - 创建嵌套映射类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69437516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com