我有一个函数,它接收一个字符串数组并返回一个对象,该对象的键是字符串,每个值都是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
定义正确的返回值。我必须使用泛型或以某种方式动态生成该类型。有可能吗?
答案 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