我有一个旧版 API,如下所示(游乐场链接 https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gWwQQwHYBMCMUC8UDeAUFCVAMYLoBcUARAiFAGYCWATgM7DmIoa0AaYqWRsA5phpc2LVGKGkoosQCYaAIzhwANhDSEAvoUKhIsXmnQrcBYSQrU6DKBwhk4GHkkuC7zLVLAMnIKpOqiNKgArgjqEGyGxqbQ8N6eeKl8WFAAPuZpVsZMUahkwCweUBAAHm5RwBAAFA40mZYA2rQOtAC6AkriHFRojAD0AFRQAO5wUdroUNosANbQwHAuQR5i2ozJUMAAFiwcUOOjAJS2iu6oHDoQAHTacGKNyhwXiYQ1dQ2N9EYrE43HcBUEBAmUC0YFOCBOHFkYigYDYcFhZ1GBi+QA)...
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 */})
有什么方法可以输入检查args
的参数execute
函数不改变函数的参数列表?
Thanks
Use 提取 https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union (操场 https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gWwQQwHYBMCMUC8UDeAUFCVAMYLoBcUARAiFAGYCWATgM7DmIoa0AaYqWRsA5phpc2LVGKGkoosQCYaAIzhwANhDSEAvoUKhIsXmnQrcBYSQrU6DKBwhk4GHkkuC7zLVLAMnIKpOqiNKgArgjqEGyGxqbQ8N6eeKl8WFAAPuZpVsZMUahkwCweUBAAHm5RwBAAPDBV1Q0YHPlZANq0DrQAugB8ABQONDACSuIcNADyCCzAjQCibWzIZc0WGFP45JQTUAZDU32UtEMAlLaK7qgcOhAAdNpwYmOUU8ocV4mENTqDRG9EYrE43HcBUEBGmEhotAA1hx0DDlGooEEotADH8AbUyPUICDnK57ugvFkYfsmAE6ABHADuEBh4TYNAALNZcYQgA):
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 })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)