Below is a function that I am working with in the TypeScript playground:
function myf(): Record<string, string> {
return {
prop1: "a",
prop2: "b"
}
}
This function is pure and simply returns a dictionary value. My goal is to extract a type definition from the return type of this function, specifically {prop1: string, prop2: string}
.
I attempted to do so using:
type MyType = ReturnType<typeof myf>;
however, this results in a generic type {[key: string]: string}
, which although correct, does not meet my goals:
https://i.sstatic.net/lzZ36.png
If I use my function without specifying a return type as shown below (playground):
function myf() {
return {
prop1: "a",
prop2: "b"
}
}
I get a valid result:
https://i.sstatic.net/9UEzR.png
However, in this case, I lose type checking on my return value.
My question is, is it possible to have both type checking on the return value and somehow infer the return type outside of the function? Ideally, I would like something similar to the example below (with intellisense for myvar
):