可能没有必要,但我一直在思考如何概括或提取/扩展/重用这些类似类型定义的部分,因为我发现它们读起来很混乱。
const zip = <T, K>(arr1: readonly T[], arr2: readonly K[]): Array<[T, K]> => arr1.map((k, i) => [k, arr2[i]])
const zipObj = <T extends string, K>(arr1: readonly T[], arr2: readonly K[]): { [key: string]: K} =>
Object.fromEntries(zip(arr1, arr2))
// usage
const names = ['bob', 'sally', 'dave'] as const
const ages = [50, 40, 30] as const
const myEntries = zip(names, ages) // [['bob', 50], ['sally', 40], ['dave', 30]]
const myObj = zipObj(names, ages) // { 'bob': 50, 'sally': 40, 'dave': 30 }
zipObj
要求 T
是有效的键(因此 T extends string
或 T extends string | number | symbol
)理想情况下,我希望能够将其提取到一个单独的定义中。我可以轻松做到:
type ZipFunction = <T, K>(arr1: readonly T[], arr2: readonly K[]) => Array<[T, K]>
但是我不确定从这里到哪里去覆盖
T
和 ZipObjFunction
的返回类型。
你可以尝试:
type ZipObjectFunction = <T, K>(arr1: readonly T[], arr2: readonly K[]) => Object.fromEntries<Array<[T, K]>>
这能解决问题吗?