Search code examples
typescripttype-assertion

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

?


Solution

  • 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!