简体   繁体   中英

Typescript Type Assertion

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 = {};

?

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 eg

let foo: Foo | any = {};
foo = {}; // OKAY!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM