A beginner lesson about T vs any in Typescript

· typescript  · 1 min read

T vs any in TypeScript

A beginner lesson about T vs any in Typescript

This is something that went in my head while learning TypeScript.

Both means “could be any kind of type”, but there is one huge difference.

Similarities of “any” and generic “T”

  • any is never constrained
  • generic is always under constraint somewhere

Example with generic T

Let’s say we want a method that returns an array with only one element :

function oneElementArrayOf<T>(stuff: T): [T] {
  return [stuff];
}

T is under constraint : “stuff” can only be of T type, and the return type can only be an array of T

In other word, if you see thesomewhere, there is another place where it will be used, in the args or the returned type.

Same example with any

The same code with any

function oneElementArrayOf(stuff: any): [any] {
  return [43]; // valid!!
}

“any” is not constrained by anything. The code is valid (TS valid I mean), despite not achieving the initial goal.

Summary

That was quick, but I hope it helped.

To sum up,

  • “any” means “zero constraint”.
  • “T” means “has at least one constraint”.

Hope it helped!

David.

Share:
Back to Blog

Related Posts

View All Posts »