gpt4 book ai didi

typescript - 如何为条件类型赋值?

转载 作者:行者123 更新时间:2023-12-03 17:08:14 26 4
gpt4 key购买 nike

我正在尝试编写一个函数,使得第一个参数是 boolean ,并取决于此参数是否为 truefalse ,第二个参数是一个接受 string 的函数或 string[] .
这是我的尝试:

type P<B extends boolean> = B extends true ? string[] : string

function callback<B extends boolean>(b: B, t: (f: P<B>) => void) {
const file = 'file'
if (b) {
t([file]) // <-- Error: Argument of type 'string' is not assignable to parameter of type 'P<B>'.
} else {
t(file) // <-- Error: Argument of type 'string[]' is not assignable to parameter of type 'P<B>'.
}

}

callback(false, (f: string) => {}) // <-- No problem, resolves the correct argument type
callback(true, (f: string[]) => {}) // <-- No problem, resolves the correct argument type
这适用于在调用函数时解析正确的参数类型。但是,在函数内部,TS 编译器给了我一个错误,即它无法将条件类型解析为 stringstring[] .这样做的正确方法是什么?
Playground link .

最佳答案

这是通过传递带有两个参数的对象来实现的一种方法。通过使用具有 true 的类型和一个签名或 false另一方面,编译器可以通过测试b来区分对象。属性(property)。

type f = { b: false, t: (f: string) => void };
type t = { b: true, t: (f: string[]) => void };
type fOrT = f | t;

function callback(x: fOrT) {
const file = 'file'
if (x.b) {
x.t([file])
} else {
x.t(file)
}

}

callback({ b: false, t: (f: string) => {} })
callback({ b: true, t: (f: string[]) => {} })
TypeScript Playground

关于typescript - 如何为条件类型赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64893755/

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