Luk*_*kas 5 typescript typescript-typings
我有一个函数,它接收字符串数组并返回一个对象,其键是字符串,每个值是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 可以帮助您获得更严格的返回对象类型
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |