gpt4 book ai didi

typescript - 如何在 typescript 中对联合类型编写过滤器

转载 作者:搜寻专家 更新时间:2023-10-30 21:13:49 25 4
gpt4 key购买 nike

我有以下示例来说明我想要得到的东西。

const v1: { type: "S"; payload: string } = { type: "S", payload: "test" };
const v2: { type: "N"; payload: number } = { type: "N", payload: 123 };

type Actions = typeof v1 | typeof v2;

const findByType = <A extends Actions>(type: A["type"]) => (
action: Actions
): action is A => action.type === type;

const filterWithBothNameAndType = [v1, v2].filter(findByType<typeof v1>("S"));
console.log(filterWithBothNameAndType[0].payload.trim());

const findByTypeDoesntWork = <A extends Actions, T extends A["type"]>(type: T) => (
action: Actions
): action is A => action.type === type;

const filterWithJustType = [v1, v2].filter(findByTypeDoesntWork("S"));
console.log(filterWithJustType[0].payload.trim());

typescript playground

我的函数 findByType 具有正确的类型信息,我的函数 filterWithJustType 具有我喜欢的 api,但它丢失了类型信息。我希望 api 只是 filter("S") 而不传递通用类型。到目前为止it looks like它只适用于类和 instaceof 但我想让它适用于普通对象。

最佳答案

您可以使用 ExcludeExtract,如 docs 中所述,例如:

type T00 = Exclude<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "b" | "d"
type T01 = Extract<"a" | "b" | "c" | "d", "a" | "c" | "f">; // "a" | "c"

type T02 = Exclude<string | number | (() => void), Function>; // string | number
type T03 = Extract<string | number | (() => void), Function>; // () => void

关于typescript - 如何在 typescript 中对联合类型编写过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47192398/

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