TypeScript:需要一个类型的所有键作为数组 [英] TypeScript: Require all keys of a type as array

查看:33
本文介绍了TypeScript:需要一个类型的所有键作为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个字符串数组,该数组应始终包含给定类型的所有键.

I'd like to generate an array of strings that should always contain all keys of a given type.

interface User {
  id: number
  name: string
}

// should report an error because name is missing
const allUserFields: EnforceKeys<User> = ["id"];

type EnforceKeys<T> = any; // what to use here?

我试过 type EnforceKeys;= Array<keyof T> 并且虽然该类型为我提供了自动完成功能并报告非法键,它不会强制执行所有键.然而,这正是我想要的.

I've tried type EnforceKeys<T> = Array<keyof T> and while that type gives me auto-completion and reports illegal keys, it doesn't enforce all keys. However, that's what I want.

这是我想要拥有它的背景.

And here is the background why I want to have it.

// this type contains updatable fields and can be given to api/client interface
type UserUpdate = Pick<User, "name">

// this should always contain all keys to keep it in sync 
const updateableFields: EnforceKeys<UserUpdate> = ['name']

// simple example for using the array to just update updatable fields
function updateUser(user: User, update: UserUpdate) {
  updateableFields.forEach(field => {
    user[field] = update[field];
  });
  // ...
}

推荐答案

在@jcalz 的评论之后,我开发了这段代码,它实际上做了它应该做的事情,但有点冗长.

After the comment of @jcalz I've developed this piece of code that actually does what it should do, while being a little bit verbose.

type BooleanMap<T> = { [key in keyof T]: boolean }

const updatableFieldsConfig: BooleanMap<UserUpdate> = {
  name: true,
}

const updatableFields = Object.entries(updatableFieldsConfig)
  .filter(([key, value]) => !!value)
  .map(([key, value]) => key)
// ["name"]

基本思想是我们可以为给定的类型强制执行一个配置对象,该对象可以转换为一个键数组.这对我的用例来说更好,因为它允许开发人员选择加入和退出特定字段,同时强制配置每个新字段.

The basic idea is that we can enforce a configuration object for a given type that can be transformed into an array of keys. That is even better for my use case, since it allows the developer to opt in and out for specific fields, while enforcing that every new field gets configured.

这里是更可重用的代码:

And here is the more reusable code:

interface UserUpdate {
  name: string
}

const updatableFields = getWhitelistedKeys<UserUpdate>({
  name: true,
})

function getWhitelistedKeys<T>(config: { [key in keyof T]: boolean }) {
  return Object.entries(config)
    .filter(([_, value]) => !!value)
    .map(([key]) => key as keyof T)
}

对我来说已经足够好了.

Looks good enough for me.

这篇关于TypeScript:需要一个类型的所有键作为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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