0

Assuming I have an interface with many variables, and I don't wanna initialize all of them when I use it, so I just put the any type assertion. I just wanna know if these two are the same or not:

eg:

export interface Foo {
  a: string;
  b: number;
  c: Bar[];
  d: string;
  e: Bar;
}

Is

let foo: Foo = {} as any;

the same with

let foo: Foo | any = {};

?

2 Answers 2

1

No. They are not the same.

First

The following is safer:

let foo: Foo = {} as any;

You can't do

let foo: Foo = {} as any;
foo = {}; // Error  

Second

The following exposes you to danger e.g.

let foo: Foo | any = {};
foo = {}; // OKAY!
Sign up to request clarification or add additional context in comments.

Comments

1

They are not the same. You have to look at how the compiler will break down each statement.

  1. Statement
  2. Variable Name
  3. Type declarator
  4. Declared Type
  5. Assign Symbol
  6. Value
  7. Cast Operator
  8. Cast Type

So

 | 1 | 2 |3| 4       |5| 4 | 5 | 6
  let foo : Foo       = {}   as  any;
  let foo : Foo | any = {};

So the first statement does not allow any as a Type(4) for the value stored in the variable(2) where the second one does.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.