相关疑难解决方法(0)

根据 TypeScript 中的参数动态生成返回类型

我有一个函数,它接收字符串数组并返回一个对象,其键是字符串,每个值是undefined

function getInitialCharacteristics(names: string[]): ??? {
  return names.reduce((obj, name) => ({ ...obj, [name]: undefined }), {});
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

const result = getInitialCharacteristics(["hello", "world"]);
// result == { hello: undefined, world: undefined }
Run Code Online (Sandbox Code Playgroud)

现在我想知道如何定义使用 TypeScript 的正确返回值getInitialCharacteristics。我必须使用泛型或以某种方式动态生成该类型。那可能吗?

typescript typescript-typings

5
推荐指数
1
解决办法
2125
查看次数

标签 统计

typescript ×1

typescript-typings ×1