T vs any in TypeScript

Article originally published here : https://alsohelp.com/blog/t-vs-any-in-typescript Something you probably already heard about, but this is my way of seeing it. Article below 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(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 the somewhere, 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.

May 25, 2025 - 02:10
 0
T vs any in TypeScript

Article originally published here : https://alsohelp.com/blog/t-vs-any-in-typescript

Something you probably already heard about, but this is my way of seeing it.

Article below

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 the somewhere, 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.