我正在开发一个打字脚本项目,我遇到了这样一种情况,我想对函数的第二个参数data
进行类型推断和完成,该函数依赖于函数的第一个参数type
.
以下是示例类型
enum MessageType {
FOO = "FOO",
BAR = "BAR",
BAZ = "BAZ",
}
interface DataFoo {
type: MessageType.FOO
payload: string
}
interface DataBarOrBaz {
type: MessageType.BAR | MessageType.BAZ
name: string
age: number
}
type Data = DataFoo | DataBarOrBaz
这是我正在开发的函数,我希望自动完成data
参数
function emit<T extends MessageType>(type: T, data: ???) {}
预期的结果是这样的
emit(MessageType.FOO, {
payload: "hello world"
// with autocomplete for payload in DataFoo
})
emit(MessageType.BAR, {
name: "hello"
age: 18
// with autocomplete for name and age in DataBarOrBaz
})
emit(MessageType.BAZ, {
name: "hello",
age: 18
// with autocomplete for name and age in DataBarOrBaz
})
然而,当我try 在TypeScrip中使用Extract
实用程序类型实现预期结果时,type
字段是MessageType
的联合的接口不起作用
function emit<T extends MessageType>(type: T, data: Omit<Extract<Data, {type: T}>, "type">) {}
emit(MessageType.FOO, { // the type for data becomes Omit<DataFoo, "type">
payload: "hello world"
// works as intended
})
emit(MessageType.BAR, { // the type for data becomes Omit<never, "type">
// expecting the type to be Omit<DataBarOrBaz, "type">
})
emit(MessageType.BAZ, { // the type for data becomes Omit<never, "type">
// expecting the type to be Omit<DataBarOrBaz, "type">
})
有没有办法使用TypeScrip v5来实现这一目标?