我试图通过选取特定的对象键值,根据"props 键值"生成"动态对象键值".

假设我通过{ name: 'someEntity', unrelatedKey: 123 }分,我想返回{ someEntity: 'ok' }分.如果返回值是typescript类型定义的,那么该怎么做呢?我try 过类似的方法,但不起作用:

type GetExampleProps = {
  name: string
  unrelatedKey: number
}

type GetExampleRes<T> = {
  [key: T]: string
}

function getExample<T extends GetExampleProps> (props: T): GetExampleRes<T['name']> {
  return {
    [props.name]: 'ok'
  }
}

const example = getExample({ name: 'someEntity', unrelatedKey: 123 })

example.someEntity  // should be valid type string
example.hello       // should be invalid, missing key

推荐答案

目前,如果没有类型断言,我无法做到这一点,但作为临时解决方案,它是:

type GetExampleProps<T extends PropertyKey = string> = {
  name: T;
  unrelatedKey: number;
};

function getExample<T extends PropertyKey>(
  props: GetExampleProps<T>
): {
  [K in T]: string;
} {
  const toRet = {
    [props.name]: "a string",
  };

  return toRet as { [K in T]: string };
}

const example = getExample({ name: "someEntity", unrelatedKey: 123 });

example.someEntity;
example.hello; // Property 'hello' does not exist on type '{ someEntity: string; }'

Javascript相关问答推荐

JS、C++和C#给出不同的Base 64 Guid编码结果

确定MutationRecord中removedNodes的索引

vscode扩展-webView Panel按钮不起任何作用

过滤对象数组并动态将属性放入新数组

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

如何在Obsidian dataview中创建进度条

如何在Vue 3中创建自定义 Select 组件,并将选项作为HTML而不是props 传递?

单个HTML中的多个HTML文件

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

查询参数中的JAVASCRIPT/REACT中的括号

将数组扩展到对象中

每隔3个项目交替显示,然后每1个项目交替显示

为什么我的Navbar.css没有显示在本地主机页面上?

ComponentWillReceiveProps仍在React 18.2.0中工作

TypeORM QueryBuilder限制联接到一条记录

Promise.race()返回已解析的promise ,而不是第一个被拒绝的promise

正则表达式以确定给定文本是否不只包含邮箱字符串

Firefox的绝对定位没有达到预期效果

正在发出错误的URL请求

观察子组件中的@Output事件emits 器?