键和值相同的对象的类型 [英] Typings for an object where keys and values are the same

查看:17
本文介绍了键和值相同的对象的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在打字稿中是否有一种方法可以表达一个函数的类型,该函数接受一个字符串列表,并创建一个对象,其中每个键的值都是键本身:

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.

TS 游乐场链接

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)

另外,为了清楚起见,我会避免使用像 type 这样的保留字作为变量或函数参数.它需要我看两次以确保 type 不是类型,而是一个值.

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.

这篇关于键和值相同的对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆