繁体   English   中英

Typescript 中单个键值对的类型是什么?

[英]What is the type for a single key-value pair in Typescript?

在 TypeScript 中,我知道如何声明一个多键值对对象

{ [key: string]: any }

如何声明单个键值对?

我想要支持的特定用例是一个道具,它可以是string数组或单个密钥对对象。

例如:

const searchArray = [
  'name', 
  {stats: 'resolution'},
  'uptime',
  {config: 'interface'},
];

起初我认为解决方案很简单

Record<string,string>

所以我的searchArray的最终声明是

interface Props {
  (...)
  searchArray: (string | Record<string,string>)[],
}

但我希望它会拒绝这个,因为我在一个对象中发送了两个密钥对,但它接受了。

searchArray={[
 'name',
 'bitrate',
 {stats:'resolution', stats:'frameRate'}
]}

每个对象应该只接受一对密钥。 应接受以下内容

searchArray={[
 'name',
 'bitrate',
 {stats:'resolution'}, 
 {stats:'frameRate'}
]}

谢谢!

据我所知,没有办法将string索引类型限制为只有一个属性条目,但这里有两个替代建议:

  1. 使用元组

TS游乐场

type Entry<Key extends PropertyKey, Value> = [Key, Value];

const searchArray = [
  'name', 
  ['stats', 'resolution'],
  'uptime',
  ['config', 'interface'],
] satisfies (string | Entry<string, string>)[];

  1. 或者——稍微冗长一点(但可能更清晰,这取决于你的观点)——使用具有keyvalue属性的对象类型:

TS游乐场

type Entry<Key extends PropertyKey, Value> = {
  key: Key;
  value: Value;
};

const searchArray = [
  'name', 
  { key: 'stats', value: 'resolution' },
  'uptime',
  { key: 'config', value: 'interface' },
] satisfies (string | Entry<string, string>)[];

另请参阅:TS 手册中的泛型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM