Typescript: Why does `as unknown as x` work

Basics

A as B works if A can be assigned to B OR B can be assigned to A.

Your case

data as Item will only work if data can be assigned to Item OR Item can be assigned to data. Since this is not true data as Item is an error.

data as unknown works because anything can be assigned to unknown and therefore data can be assigned to unknown. => 1

unknown as Item works because again anything can be assigned to unknown and therefore Item can be assigned to unknown. => 2

data as unknown as Item works because 1 && 2 are allowed.

More

This is known as double assertion.

References

  • Double Assertion https://basarat.gitbook.io/typescript/type-system/type-assertion#double-assertion
  • unknown type : https://www.youtube.com/watch?v=wOa67sZyO54

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)