我有一个元组,包含两个对象。
const repos = [
{ name: 'react', type: 'JS' },
{ name: 'angular', type: 'TS' },
] as const
const RepoTypes = typeof repos
const jsRepoTypes = FilterRepos<'JS'> // Should return the type object containing only JS我正在寻找一些通用实用程序类型( FilterRepos<T> ),在这里我可以传递type参数,它应该返回过滤后的元组类型。
发布于 2022-08-21 06:19:29
通过过滤出不匹配的元组元素,我们可以使用尾递归类型来构造元组。
type FilterRepos<
T extends string,
REPOS extends readonly any[] = typeof repos
> =
REPOS extends readonly [infer L, ...infer R]
? L extends { type: T }
? [L, ...FilterRepos<T, R>]
: FilterRepos<T, R>
: []
type JsRepoTypes = FilterRepos<'JS'>
// type JsRepoTypes = [{
// readonly name: "react";
// readonly type: "JS";
// }, {
// readonly name: "vue";
// readonly type: "JS";
// }]https://stackoverflow.com/questions/73432063
复制相似问题