从类型联合定义打字稿功能签名

时间:2020-09-21 09:02:00

标签: typescript generics types typescript-typings conditional-types

我想通过类型的并集定义函数的类型:

type MyEvent =
| { type: 'hello', payload: {} }
| { type: 'start', payload: { date: Date } }


type On<Event> = Event extends { type: infer EventType, payload: infer EventPayload }
  ? (type: EventType, callback: (payload: EventPayload) => void) => void
  : never

const on: On<MyEvent>
on('hello', (payload) => void)

但是编译器将第一个参数的类型定义为“从不”

On返回一个看起来不错的类型。我也尝试了返回的原始类型,结果相同:

type RawOn =
| ((type: "hello", callback: (payload: {}) => void) => void)
| ((type: "start", callback: (payload: { date: Date }) => void) => void)

const raw_on: RawOn
raw_on('hello', (payload) => void)

如何定义“函数签名的联合类型”?

Playground

1 个答案:

答案 0 :(得分:0)

感谢@cherryblossom提供解决方案:

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void)
  ? I
  : never

// --------------------------------------------------
  
type MyEvent =
| { type: 'hello', payload: {} }
| { type: 'start', payload: { date: Date } }


type On<Event> = UnionToIntersection<
  Event extends { type: infer EventType, payload: infer EventPayload }
    ? (type: EventType, callback: (payload: EventPayload) => void) => void
    : never
>

const init_on = (): On<MyEvent> => {}
const on = init_on()

// OK
on('hello', (payload: {}) => {})
on('start', (payload: { date: Date }) => {})

// ERROR (that is OK)
on('hello', (payload: { date: Date }) => {})
on('bad-event', (payload: {}) => {})

Playground