tsafe
GitHub
  • 👋What is tsafe?
  • ⚙️How to import
  • assert
  • Equals
  • id
  • is
  • objectKeys
  • exclude
  • isAmong
  • symToStr
  • ReturnType
  • Parameters
  • Param0
  • typeGuard
  • capitalize/uncapitalize
  • MethodNames
  • isPromiseLike
  • flip
  • objectEntries
  • objectFromEntries
  • UnionToIntersection
  • 🚧withDefaults
  • 📉UnpackPromise
Powered by GitBook
On this page
  • Used with async function
  • Used with function that can be undefined

Was this helpful?

Edit on GitHub

ReturnType

Like the builtin helper but more convenient to use.

PrevioussymToStrNextParameters

Last updated 6 months ago

Was this helpful?

There is two major pain point with :

Used with async function

If you have a function like:

type Shape = {};
async function getShape(): Promise<Shape> {
	return {};
}

And you are trying to extract Shape, when you use the default return type:

type shape = ReturnType<typeof getShape>;
//    ^ shape is Promise<Shape> 😤

With tsafe's ReturnType

import type { ReturnType } from "tsafe";

type shape = ReturnType<typeof getShape>;
//    ^ shape is Shape 😊

Used with function that can be undefined

Let's say we have an interface defined as such:

export type Api = {
	getShape?: () => Shape;
};

And we want to extract the type Shape, using the default ReturnType we have to do:

type shape = ReturnType<NonNullable<Api["getShape"]>>;

With the ReturnType of tsafe you don't need NonNullable

import type { ReturnType } from "tsafe";

type shape = ReturnType<Api["getShape"]>;
the default ReturnType