Imagine having a function like this:
function fetchUser() {
return {
username: "johndoe",
email: "johndoe@example.com"
}
}
You can create a type based on the return value:
type User = ReturnType<typeof fetchUser>;
But, when you hover over the function call or user
below:
const user = fetchUser();
they are automatically given the type:
{
username: string,
email: string
}
However, it would be more beneficial if they were typed as User
. Sometimes, it's important to know that an object was returned by a specific function. This is because functions may only return certain properties of the inferred types, and the type system may not be able to specify constraints like non-negative age.
So, ideally we could specify the User
type in a way that when applying it to a function like:
function handleUser(user: User) {
// ...
}
The following would be accepted:
handleUser(fetchUser());
but this would not:
handleUser({
username: "johndoe",
email: "johndoe@example.com"
});
This would result in an error. It's uncertain if TypeScript supports this feature or if it aligns with its design principles, but it would be useful. Is there a way to achieve this?
I have attempted different methods, but they have led to circular definition errors. If this feature does not exist, I will consider making a feature request. I am hoping for a syntax like:
function fetchUser(): infer User {
or
type User = ReturnType<typeof user as const>;