简体   繁体   中英

Dynamically generate return type based on parameter in TypeScript

I have a function that receives an array of strings and returns an object whose keys are the strings and every value is undefined :

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

Example usage:

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

Now I wonder how I can define the proper return value for getInitialCharacteristics using TypeScript. I'd have to use generics or somehow dynamically generate that type. Is that possible?

If you are going to call this function with constants or string literals, typescript can help you get a stricter type for the return object

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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