[英]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
索引类型限制为只有一个属性条目,但这里有两个替代建议:
type Entry<Key extends PropertyKey, Value> = [Key, Value];
const searchArray = [
'name',
['stats', 'resolution'],
'uptime',
['config', 'interface'],
] satisfies (string | Entry<string, string>)[];
key
和value
属性的对象类型: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.