gpt4 book ai didi

javascript - 如何匹配联合类型中的不同键

转载 作者:行者123 更新时间:2023-12-01 00:33:31 27 4
gpt4 key购买 nike

我不知道如何问这个问题......但希望代码示例应该能澄清我的问题:

type A = {| +type: "A", +payload: "PA" |};
type B = {| +type: "B", +payload: "PB" |};

type Actions = A | B;

function dispatch<T: Actions>(type: $PropertyType<T, 'type'>, payload: $PropertyType<T, 'payload'>) {
}

dispatch("A", "PA"); // ok
dispatch("B", "PB"); // ok

dispatch("A", "PB"); // this doesn't error, but I'd like to
dispatch("B", "PA"); // this doesn't error, but I'd like to

dispatch("C", "PC"); // this errors properly

https://flow.org/try/#0C4TwDgpgBAglC8UDeAfKBqUkBcUBEMeANBmAIYgA2A9mQCa54AKhUKAvgNwBQW0AQgmRpM4CI37FSFGvUZNJbLt15jYAY2ABLagDsAzkLhp+PbgDMArrs07dUOlv3lg6gBYAeACq4YtvfoAfAAUfLgAJEwATtSQUaBeYt4kAOR8KYEk5FS0DFCRMXEJSV6p2bJ0GQCUyNzs3FDcjs5krm7BBFLMhFWcUAD0-VDUANZNTi7uHZIkzJK9A0OjKs2T7Z2zCngLg1AQUTFR4y1t010s2327+4crE61TeADC5y87QzfUUUA

最佳答案

您需要一种允许根据键查找类型的类型,不幸的是,我认为标记的联合不允许这样做。例如,您可以将函数更改为:

type ActionsLookup = {
A: A,
B: B,
};
type Actions = $Values<ActionsLookup>;

function dispatch<K: $Keys<ActionsLookup>>(
type: K,
payload: $ElementType<$ElementType<ActionsLookup, K>, 'payload'>
) {}

关于javascript - 如何匹配联合类型中的不同键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326640/

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