问题描述
我有一个字符串键keyof E({a: SomeType<'a'>, b: SomeType<'b'>}['a'|'b'])上查找其值,变为SomeType<'a'> | SomeType<'b'>.在我们的情况下,SomeType<Q>是E[Q] extends P ? Q : never,如果E[Q]与P匹配,则得出Q,否则为never.因此,我们得到了keyof E中Q匹配P的Q值的并集.应该只有其中之一(如果枚举没有两个具有相同值的键).
Let's explain {[Q in keyof E]: E[Q] extends P ? Q : never}[keyof E] more fully. Generally a type like {[Q in keyof E]: SomeType<Q>}[keyof E] will be the union of SomeType<Q> for all Q in keyof E. You can cash it out with a concrete type if that makes more sense... if E is {a: string, b: number}, then {[Q in keyof E]: SomeType<Q>} will be {a: SomeType<'a'>, b: SomeType<'b'>}, and then we look up its values at keys keyof E, which is {a: SomeType<'a'>, b: SomeType<'b'>}['a'|'b'], which becomes SomeType<'a'> | SomeType<'b'>. In our case, SomeType<Q> is E[Q] extends P ? Q : never, which evaluates to Q if E[Q] matches P, and never otherwise. Thus we are getting the union of Q values in keyof E for which E[Q] matches P. There should be just one of those (if the enum doesn't have two keys with the same value).
进行手动评估BackendObject<typeof FooNames, FooTypes>以查看其发生情况可能对您很有用.
It might be useful for you to go through the exercise of manually evaluating BackendObject<typeof FooNames, FooTypes> to see it happen.
您可以验证其行为是否符合预期.希望能有所帮助.祝你好运!
You can verify that it behaves as desired. Hope that helps. Good luck!
这篇关于在Typescript中将两种类型完美地组合成一个界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!