简体   繁体   English

打字稿类型断言

[英]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. 假设我有一个包含许多变量的接口,并且在使用它时我不想初始化所有变量,所以我只需要放置any类型的断言。 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. 因此,第一个语句不允许 any为类型(4),用于存储在变量(2),其中所述第二个确实的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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