【发布时间】:2017-09-25 16:34:50
【问题描述】:
假设我有一个符合定义类型的输入:
interface Person {
name: string;
age: number;
}
现在,我想要一个函数来接受一个键值对数组,例如:
function acceptsPersonProperties(tuple: Array<PersonTuple>) { ... }
// this should be fine:
acceptsPersonProperties([['name', 'Bob'], ['age', 42]]);
// this should give a compile-time error:
acceptsPersonProperties([['name', 2], ['age', 'Bob']]);
当然,我可以手动输入,例如:
type PersonTuple = ['name', string] | ['age', number];
但是如果类型(例如Person)是一个模板变量,那么元组如何表示为mapped type呢?
function acceptsPropertiesOfT<T>(tuple: Array<MappedTypeHere<T>>) { ... }
为了避免 X-Y 问题,真正的用例是这样的:
let request = api.get({
url: 'folder/1/files',
query: [
['fileid', 23],
['fileid', 47],
['fileid', 69]
]
});
解析为"/api/folder/1/files?fileid=23&fileid=47&fileid=69",但我想输入,所以它不允许额外的属性(file_id)并检查类型(没有字符串作为fileid)。
【问题讨论】:
标签: typescript types