Share this
Twitter Shield
GraphQL Editor Logo

Advanced typescript tutorial - return based on args

December 12, 2018 by Artur

← back to blog

Hello This is third article of 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
}

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

const result = myFunc({
  x: 1,
  y: 1,
})

And the intellisense for such function is Typescript return correct args

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

This part is super short as I can provide infinite number of generic functions usages. Thank you for your support on `/r/typescript/ reddit ! It gives me power to write blog-post-a-day!

Hey, have a minute?

Do you want to try our mock backend from GraphQL app. It is in beta phase and 100% free.

Try GraphQL Editor

Artur Czemiel
Written by Artur Czemiel GraphQL passionate. Code generation guru. Short code lover. Father. CTO. CEO. email me:[email protected]Twitter Shield
← Back to blog