1

I was going through this answer on stackoverflow

Here the author have answered: // How I tend to intialize

var foo:IFoo = <any>{};

I tried to google but I wasn't able to find any info regarding it. What does it mean the part <any>{};?

Also is {} as any equal to <any>{}?

Julian
  • 33,915
  • 22
  • 119
  • 174
Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • You are probably also better off _not_ casting to any. When you initialize the object and cast from any, presumably it's because IFoo actually has properties. You are going to catch more bugs avoiding this. – Evert Jun 15 '20 at 22:25

1 Answers1

1

Also is {} as any equal to <any>{}?

Yes, <any> is the old syntax. See Type assertions

What does it mean?

See also See Type assertions:

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually this will happen when you know the type of some entity could be more specific than its current type.

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

Type assertions have two forms. One is the “angle-bracket” syntax and the other is the as-syntax

This any trick is to get this compiling:

interface IFoo{

  someProp: string
}

var foo:IFoo = <any>{};

As this will complain as the someProp is missing:

var foo:IFoo = {}
Julian
  • 33,915
  • 22
  • 119
  • 174