如何生成元组类型的映射类型?

时间:2017-04-27 18:19:44

标签: typescript types

假设我有一个符合定义类型的输入:

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];

但是如果type(例如Person)是模板变量,那么元组如何表示为https://myinstance.salesforce.com/?ec=302&startURL=%2

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)。

1 个答案:

答案 0 :(得分:4)

您无法使用元组类型执行此操作。元组的右侧将始终被推广为Person中所有可能值的并集。

但是,如果您稍微更改API,则可以使其正常工作:

interface Person {
  name: string;
  age: number;
}

function acceptsPersonProperties(tuple: Partial<Person>[]) { }

// this should be fine:
acceptsPersonProperties([{ name: 'Bob' }, { age: 42 }]);

// this should give a compile-time error:
acceptsPersonProperties([{ name: 2 }, { age: 'Bob' }]);
相关问题