DEV Community

Artur Czemiel
Artur Czemiel

Posted on • Originally published at blog.graphqleditor.com

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.

Top comments (0)