是否可以定义这个函数
function magic(...propertyNames:string[]): { ????? : any }
{
....
}
在这样的情况下,返回的类型将具有propetyNames 中列出的属性?
例如:
type ResultType = {alpha:any, bravo:any};
let res = magic('alpha', 'bravo'); // res is compatible with ResultType
这是一个可能的解决方案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] 删除。
我来说两句