3 回答

TA贡献1824条经验 获得超8个赞
这个答案非常(过度)复杂,但你最终会得到这种类型:
const userDetails = parseFields(fields);
type Z = typeof userDetails;
// type Z = {
// address: {
// city: "Tulsa" | "Norman"; // Added to test
// state: "OK";
// };
// } & {
// firstName: "Bob";
// lastName: "Smith";
// }
它需要制作fields as const:
const fields = [
...
] as const;
还有……实际的打字:
type AddressKeys = 'city' | 'street' | 'state' | 'suite' | 'zipCode';
type _ParseFieldsResultKeys<T extends readonly FieldProps[]> = {
[K in keyof T]: T[K] extends { name: string } ? T[K]['name'] : never;
}[Exclude<keyof T, keyof []>];
type _GetParseFieldResultValue<T extends readonly FieldProps[], N> =
Extract<T[keyof T], { name: N }> extends { value: infer V } ? V : never;
type ParseFieldsResult<T extends readonly FieldProps[]> = {
address: {
[N in Extract<_ParseFieldsResultKeys<T>, AddressKeys>]: _GetParseFieldResultValue<T, N>;
}
} & {
[N in Exclude<_ParseFieldsResultKeys<T>, AddressKeys>]: _GetParseFieldResultValue<T, N>;
};
const parseFields = <T extends readonly FieldProps[]>(fields: T): ParseFieldsResult<T> => {
使用它可能不是一个好主意。但是:游乐场链接
编辑:意识到我们不需要实际的字符串文字类型,只需要string我们可以摆脱_GetParseFieldResultValue并仍然得到的值:
type Z = {
address: {
city: string;
state: string;
};
} & {
firstName: string;
lastName: string;
}

TA贡献1757条经验 获得超7个赞
在 parseFields 函数中,你有一个 K.. 的返回类型,它是一个空对象......你不应该传入 FieldProps 吗?
const parseFields = <T extends any[], K extends object = {}>(fields: T): **FieldProps** => {

TA贡献1946条经验 获得超3个赞
您在此处使用通用方法,并将 K 的默认类型设置为 {},这就是您在悬停时看到 {} 的原因。
您可以通过正确调用该方法来实现您正在寻找的东西。像这样:
const userDetails = parseFields<FieldProps[], {
"firstName": string,
"lastName": string,
"address": {
"city": string,
"state": string
}
}>(fields);
添加回答
举报