gpt4 book ai didi

TypeScript:基于元组获取嵌套属性的类型

转载 作者:行者123 更新时间:2023-12-05 00:55:20 24 4
gpt4 key购买 nike

在 TypeScript 中有没有办法根据一些元组来获取嵌套属性的类型?给定以下示例,假设元组是 ["bs", 0, "c"],那么类型应该是 boolean(或 ["bs", 0, "ds", 0, "f"] 然后是 number 等等)。

interface Foo {
a: string;
bs: {
c: boolean;
ds: {
e: null;
f: number;
}[];
}[];
}

对于某些上下文,我想键入一个带有两个参数的函数,一个 path 和一个 value。对于某些对象,如果给定路径的值是一个数组,它将push value 参数。该功能的实现见this Playround .我已经在寻找一些解决方案,例如 this issue ,但我认为我的问题有点不同。

最佳答案

在 TS4.1 中将支持 recursive conditional types这使得这有点简单:

type Keys = readonly (string | number)[];
type DeepIndex<T, KS extends Keys, Fail = undefined> =
KS extends [infer F, ...infer R] ? F extends keyof T ? R extends Keys ?
DeepIndex<T[F], R, Fail> : Fail : Fail : T;

有了DeepIndex,你可以给add()下面的类型签名:

function add<KS extends Keys>(
pathToArray: [...KS],
value: DeepIndex<Foo, KS> extends Array<infer T> ? T : never
) {
const xs = path(pathToArray, foo);

if (Array.isArray(xs)) {
xs.push(value);
}
}

导致你所说的是你想要的行为:

add(["bs", 0, "ds"], { e: null, f: 1 });
/* function add<["bs", 0, "ds"]>(pathToArray: ["bs", 0, "ds"], value: {
e: null;
f: number;
}): void */

add(["bs"], {});
// Argument of type '{}' is not assignable to parameter of
// type '{ c: boolean; ds: { e: null; f: number; }[]; }'.

add(["a"], {});
// Argument of type '{}' is not assignable to parameter of type 'never'.(2345)
add(["bs", 0, "c"], {});
// Argument of type '{}' is not assignable to parameter of type 'never'.(2345)

Playground link to code

关于TypeScript:基于元组获取嵌套属性的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64776269/

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