【发布时间】:2023-01-18 02:10:14
【问题描述】:
给定数组
const arr = [[0, 'foo'], [1, 'bar']] as const;
我需要值是具体的文字值,而不是string 或'foo' | 'bar'。
const value = get(arr, 0); // value type: 'foo'
我最好的尝试是
type Entry<K, V> = readonly [K, V];
type GetType<A extends readonly Entry<any, any>[], K> = A extends readonly Entry<K, infer V>[] ? V : never;
function get<K extends PropertyKey, V extends string>(arr: readonly Entry<K, V>[], id: K): GetType<typeof arr, K> {
return new Map(arr).get(id)!;
}
const arr = [[0, 'foo'], [1, 'bar']] as const;
const val = get(arr, 0);
但它导致 val 类型为 'foo' | 'bar'。
【问题讨论】:
-
this approach 是否满足您的需求?如果是这样,我可以写一个答案来解释;如果没有,我错过了什么?
-
@jcalz 是的,它很完美,非常感谢你:)
标签: arrays typescript tuples