[英]How can you use Tuple elements as keys in a Mapped Type or template literal in typescript?
是否有任何咒语可以在 typescript 中正确键入以下 function?
给定一个 function
createMap()
需要:
- 前缀(例如
foo
)- 和一个后缀元组(例如 ['a', 'b', 'c'])
调用
createMap('foo', ['a', 'b', 'c'])
返回以下映射类型:{ a: 'foo.a', b: 'foo.b', c: 'foo.c', }
function 实现非常简单,但返回类型似乎不是:
const createMap = <P extends string, S extends string[]>(prefix: P, suffixes: [...S]) => {
return suffixes.reduce((map, suffix) => ({
...map,
[suffix]: `${prefix}.${suffix}`,
}), {});
}
我知道这是不正确的,但它会天真地看起来像{ [K in S]:
${P}.${K in S} }
。
为了实现它,您必须将列表设置as const
然后您可以执行以下操作:
type CreateMap = <S extends string, A extends ReadonlyArray<string>>(s: S, a: A) => {
[K in (A extends ReadonlyArray<infer U> ? U : never)]: `${S}.${K}`
};
const createMap: CreateMap = (s, a) => {
return Object.fromEntries(a.map(key => [key, `${s}.${key}`])) as any
}
const list = ['a', 'b', 'c'] as const
const res = createMap('foo', list)
你可以在这里看到一个例子
我们可以使用映射类型来计算 function 的返回类型。我们只需要通过计算并集S[number]
来对S
中的元素进行 map。 现在可以使用每个元素K
将前缀P
与模板文字类型连接起来。
const createMap = <
P extends string,
S extends string[]
>(prefix: P, suffixes: [...S]) => {
return suffixes.reduce((map, suffix) => ({
...map,
[suffix]: `${prefix}.${suffix}`,
}), {}) as { [K in S[number]]: `${P}.${K}` }
}
const result = createMap('foo', ['a', 'b', 'c'])
// ^? const result: { a: "foo.a"; b: "foo.b"; c: "foo.c"; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.