如何根据打字稿中的数组定义映射类型?

赞迪

是否可以定义这个函数

function magic(...propertyNames:string[]): { ????? : any }
{
....
}

在这样的情况下,返回的类型将具有propetyNames 中列出的属性

例如:

type ResultType = {alpha:any, bravo:any};

let res = magic('alpha', 'bravo'); // res is compatible with ResultType
福特04

这是一个可能的解决方案magic

declare function magic<T extends string[]>(
  ...propertyNames: T
): Record<T[number], any>;

const result = magic("alpha", "bravo");

type ResultType = typeof result; // {alpha: any; bravo: any;}

测试ResultType

const t1: ResultType = {
  alpha: "foo",
  bravo: 42,
  wannaBe: 3 // error (OK)
};

然后您可以使用额外的类型参数进一步限制any类型Record<T[number] any>,因为any它不提供任何有用的类型。

declare function magic<T extends string[], R>(
  ...propertyNames: T
): Record<T[number], R>;

一些解释

  • T[number]给我们所有的项目值作为联合类型。例如
type T = ["alpha", "bravo"]
type TItems = T[number] // "alpha" | "bravo"
  • Record确保我们将所有项目值"alpha" | "bravo"作为属性键。
  • 可以借助通用其余参数推断元组类型

操场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章