Beware of the `any` type

Beware of the `any` type

Erick

Written by Erick /

Beware of TypeScript's any.

TS
const foo: any = 5
const bar: string = foo
console.log(typeof bar) // type is number

👉🏻 It didn't matter that we set bar to string.

Using any is safe, however, when used as a type parameter inside a generic constraint.

It's always safe to use any and unknown as a type parameter inside a generic constraint.

TS
type ItemsObject<A extends Array<unknown>> = {
  items: A
}

const itemsObject: ItemsObject<Array<string>> = {
  items: [items: ["1", "2", "3"]]
}
itemsObject // {items: ["1", "2", "3"]}

We can simplify the above with <A extends any>. That's actually the same thing as <A> I'll use T here, as it's a convention.

Simplified:

TS
type ItemsObject<T> = {
  item: T
}

const itemsObject: ItemsObject<Array<number>> = { item: [0, 3] }
itemsObject // { item: [ 0, 3 ] }

🍻 Erick