gpt4 book ai didi

Typescript基于鉴别器的窄参数类型

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

我有一个遗留 API,如下所示 ( playground link )...

type Command1 = {
cmd: "my first command",
arg1: string,
arg2: boolean
}

type Command2 = {
cmd: "my second command",
foo: string,
bar: number
}

type Command = Command1 | Command2

function execute(cmd: Command["cmd"], args:any /* would like to strongly type this */) {
console.log(args)
}

execute("my first command", {/* oops missing props */})

有没有办法在不改变函数参数列表的情况下,对execute函数的args参数进行类型检查?

谢谢

最佳答案

使用Extract<Type, Union> ( playground ):

function execute<Cmd extends Command["cmd"]>(
cmd: Cmd,
args: Omit<Extract<Command, { cmd: Cmd }>, "cmd">
) {
console.log(cmd, args)
}

// execute<"my first command">(cmd: "my first command", args: Omit<Command1, "cmd">): void
execute("my first command", { arg1: "ksd", arg2: true })

// execute<"my second command">(cmd: "my second command", args: Omit<Command2, "cmd">): void
execute("my second command", { foo: "qwe", bar: 123 })

关于Typescript基于鉴别器的窄参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70325393/

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