In the example code bellow:
const obj = {
a: () => 1,
b: () => '2'
}
type typeMap = Record<keyof typeof obj, (arg: unknown) => void>
const map: typeMap = {
a: (numberArg) => numberArg + 1,
b: (stringArg) => stringArg.length
}
I want Typescript to be aware of the function arguments types in the map
object to be the same as the return type of each key in the original obj
object. I know there is the ReturnType<>
utility, but I don't know how to use it to map each prop from obj
.
In summary, I want numberArg
to be of type number
and stringArg
to be of type string
.
You can open this code in Typescript Playground .
Use a mapped object type :
// alias for convenience
type ObjType = typeof obj;
type TypeMap = {
[K in keyof ObjType]: (arg: ReturnType<ObjType[K]>) => unknown
};
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.