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
.
TS Playground Link
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)
Also, just for clarity, I would avoid using reserved words like type
as a variable or function parameter. It required me to look twice to ensure type
is not type, but a value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…