繁体   English   中英

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

[英]Dynamically generate return type based on parameter in TypeScript

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

如果要使用常量或字符串文字调用此函数,则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

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM