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

时间:2019-07-04 07:54:33

标签: typescript typescript-typings

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

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

用法示例:

const result = getInitialCharacteristics(["hello", "world"]);
// result == { hello: undefined, world: undefined }

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

1 个答案:

答案 0 :(得分:2)

如果要使用常量或字符串文字调用此函数,则typescript可以帮助您为返回对象获得更严格的类型

function getInitialCharacteristics<T extends string>(names: T[]): Record<T, undefined>
function getInitialCharacteristics(names: string[]): Record<string, undefined> {
  return names.reduce((obj, name) => ({ ...obj, [name]: undefined }), {});
}

const result = getInitialCharacteristics(["hello", "world"]);
result.hello //ok
result.world //ok
result.helloo //err

Playground link

相关问题