DEV Community

Artur Czemiel
Artur Czemiel

Posted on • Originally published at blog.graphqleditor.com

7 1

TypeScript Tutorial - return based on args

Hello, This is the third article of the advanced typescript tutorial series. Today I'll cover basic usage of generic functions

type Point = {
  x?: number
  y?: number
  z?: number
}
const myFunc = <T extends Point>(args: T): T => {
  return args
}
Enter fullscreen mode Exit fullscreen mode

As arguments, I'll provide an object containing Point properties. This function will only return Partial of Point based on provided parameters in args argument;

const result = myFunc({
  x: 1,
  y: 1,
})
Enter fullscreen mode Exit fullscreen mode

And the intellisense for such function is
Typescript return correct args

As you see there is no z property here. Typescript already knows we provided these 2 args and it should return only them!

This part is super short as I can provide the infinite number of generic functions usages.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay