Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type annotation vs "as" keyword [duplicate]

Tags:

typescript

const names: string[] = [];
const names = [] as string[];

In TypeScript, is there a semantic difference between the above two statements? If so, when would we prefer one over the other?

like image 763
Aditya Barve Avatar asked Oct 23 '25 20:10

Aditya Barve


1 Answers

It's simple as:

  • Use type annotation if you want a new variable to be of that type.
  • Use type assertion (as keyword) if you want to tell the compiler that some expression has some specific type (even if it doesn't really).
like image 133
Nurbol Alpysbayev Avatar answered Oct 26 '25 20:10

Nurbol Alpysbayev