gpt4 book ai didi

typescript - 如何访问嵌套对象类型的公共(public)属性,这些对象本身是使用泛型类型参数访问的

转载 作者:行者123 更新时间:2023-12-05 05:46:31 26 4
gpt4 key购买 nike

下面是一个简单的泛型类型“GetA”,它只是用来索引一个类型对象以检索一个嵌套类型;它使用通用参数作为两个索引。然而,在最后,非通用索引,它会抛出类型错误(“a”不能用于索引...),即使所有可能的对象都具有索引键。我希望有人能帮助我理解。

如何制作使用相同或相似参数的 GetA 工作版本?

type GetA<
T extends keyof TestObj,
P extends keyof TestObj[T]
> = TestObj[T][P]["a"];
// Type '"a"' cannot be used to index type 'TestObj[T][P]'.ts(2536)

type TestObj = {
nested1: {
prop: {
a: "foo1";
b: "bar1";
};
anotherProp: {
a: "foo2";
b: "bar2"
}
};
nested2: {
prop: {
a: "foo3";
b: "bar3";
};
};
};

最佳答案

请记住extends并不意味着 equal .看这个例子:

type GetA<
T extends keyof TestObj,
P extends keyof TestObj[T]
> = TestObj[T][P]['a'] // expected error

type TestObj = {
nested1: {
prop: {
a: "foo1";
b: "bar1";
};
anotherProp: {
a: "foo2";
b: "bar2"
}
};
nested2: {
prop: {
a: "foo3";
b: "bar3";
};
};
};

type Result = GetA<'nested1', 'prop' & { tag: 2 }> // unknown

您可以在我的 article 中找到更多解释

'prop' & { tag: 2 }可分配给 keyof TestObj[T]同时它是 prop 的子类型.

尝试摆脱{tag: 2}你会得到预期的结果:

type Result = GetA<'nested1', 'prop'> // foo1

因此,为了更安全,需要添加条件类型:

type GetA<
T extends keyof TestObj,
P extends keyof TestObj[T]
> = 'a' extends keyof TestObj[T][P] ? TestObj[T][P]['a'] : never

type TestObj = {
nested1: {
prop: {
a: "foo1";
b: "bar1";
};
anotherProp: {
a: "foo2";
b: "bar2"
}
};
nested2: {
prop: {
a: "foo3";
b: "bar3";
};
};
};

type Result = GetA<'nested1', 'prop'> // foo1

Playground

另外,你可以让它不那么冗长:

type GetA<
T extends keyof TestObj,
P extends keyof TestObj[T],
Result = TestObj[T][P]
> = Result['a' & keyof Result]

关于typescript - 如何访问嵌套对象类型的公共(public)属性,这些对象本身是使用泛型类型参数访问的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71167059/

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