【发布时间】:2021-04-29 22:10:30
【问题描述】:
假设我有一个分析对象的接口:
type Analytics = {
identify: () => void;
page: (title: string) => void;
track: (eventName: string, props: object) => void;
}
我想实现某种队列,在我们能够执行它们之前收集所有动作。队列如下所示:
const queue = [
['identify'],
['page', 'some title'],
['track', 'event 1', { a: 'a' }],
['track', 'event 2', { b: 'b' }]
];
第一项始终是方法名称(identify、page、track),其余的是来自 Analytics 类型的方法参数。
我想到的队列界面:
type QueueItem<T extends keyof Analytics> = [T, ...Parameters<Analytics[T]>]
好的,我们试试吧:
const item1: QueueItem = ['track', 'some event', {}]
因此,我收到一个 Typescript 错误:Generic type 'QueueItem' requires 1 type argument(s)。
如果不能自动推断显式泛型类型怎么办?
const item2: QueueItem<keyof Analytics> = ['track'] // ???? no error, although "track" method expects to receive two parameters
const item3: QueueItem<keyof Analytics> = ['track2'] // ???? error as there is no such method in Analytics
没有按预期工作。 Typescript 认为项目的类型是 [keyof Analytics] | [keyof Analytics, string] | [keyof Analytics, string, object],它允许方法名称(identify、page、track)和 ['identify', 'some string', {}] 等参数的不同组合。
但它可以与函数一起使用吗?它将:
function func<T extends keyof Analytics>(method: T, ...args: Parameters<Analytics[T]>) {}
func('track') // ???? error, because track has 2 parameters
func('track', 'event', {}) // ???? no error
func('identify') // ???? no error
func('page', 'title') // ???? no error
func('page') // ???? error as we need to pass title
应该对QueueItem 类型进行哪些更改以使其按预期工作(与函数相同)?
【问题讨论】:
标签: typescript tuples