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.
The following is safer:
let foo: Foo = {} as any;
You can't do
let foo: Foo = {} as any;
foo = {}; // Error
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.
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.