本文介绍了键和值相同的对象的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在打字稿中是否有一种方法可以表达一个函数的类型,该函数接受一个字符串列表,并创建一个对象,其中每个键的值都是键本身:
Is there a way in typescript to express the typings of a function that takes in a list of strings, and creates an object where each key's value is the key itself:
const createActionTypes = (types: string[]) => {
return types.reduce((typesMap, type) => {
typesMap[type] = type
return typesMap
}, {})
}
// Input
createActionTypes(['a', 'b'])
// Output
{ a: 'a', b: 'b' }
这是我尝试过的,但没有运气:
Here's what I've tried, without luck:
const createActionTypes = <T extends readonly string[], U extends T[number]>(
types: T
): { [key in U]: U } => {
return types.reduce((typesMap, type) => {
typesMap[type] = type
return typesMap
}, {})
}
const x = createActionTypes(['a', 'b'] as const)
// Typings for x get resolved to:
{
a: "a" | "b";
b: "a" | "b";
}
推荐答案
你真的很亲近.您需要指定该值与 key
的类型相同,而不是整个 "a"|"b"
即 U
.
You are really close. You need to specify that the value is same type as key
and not the whole set "a"|"b"
which is U
.
const createActionTypes = <T extends readonly string[], U extends T[number]>(
types: T
): { [key in U]: key } => {
return types.reduce((typesMap, type) => {
typesMap[type] = type
return typesMap
}, {} as any)
}
const x = createActionTypes(['a', 'b'] as const)
这篇关于键和值相同的对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!