【发布时间】:2019-07-31 21:07:46
【问题描述】:
假设我们有一个类型T:
type T = {
type: string,
}
还有一个函数,它接受 T 的数组并返回一个对象,其键是每个 T.type 的值,其值为 T
const toMap = (...args: T[]) => args.reduce((res, t) => ({
...res,
[t.type]: t
}), {});
所以,对于这个给定的例子:
const a = { type: 'hello' };
const b = { type: 'world' };
const c = { type: 'foo' };
const map = toMap(a, b, c);
我期待这个结果
{
hello: { type: 'hello' },
world: { type: 'world' },
foo: { type: 'foo' },
}
map.hello // correct, { type: 'hello' };
// If I access an unknown property, then the compiler should:
map.bar // `property bar doesn't exist on type { hello: { ... }, world: {...}, foo: {...} }`
如何为这个函数编写类型?
【问题讨论】:
标签: javascript typescript generics typescript-typings typescript-generics