【问题标题】:Why is it possible to assign a variable of type any to a void type in typescript为什么可以在打字稿中将任何类型的变量分配给 void 类型
【发布时间】:2017-04-28 03:28:15
【问题描述】:

在 typescript 中,这段代码是有效的并且可以编译,但我不明白为什么:

const a: any = "Not void";

const x: void = a;

为什么允许这样做?文档说 void 与 any 相反,因此将 any 分配给 void 对我来说似乎是一个错误 (https://www.typescriptlang.org/docs/handbook/basic-types.html)

【问题讨论】:

    标签: typescript


    【解决方案1】:

    文档说:

    void 有点像与any相反

    所以它与any 并不完全相反。
    它还说:

    声明 void 类型的变量没有用,因为你只能 将 undefined 或 null 分配给它们

    但你也可以这样做:

    const x: void = "" as null;
    

    同样适用于any

    const x: void = "" as any;
    

    原因是当您使用any 时,您基本上告诉编译器该值可以是任何类型,并且不应对其进行类型检查。
    any 包含所有可能的类型,包括@987654327 @、undeinfedvoid

    您始终可以使用any 绕过编译器类型检查,更多示例:

    const y: number = "" as any;
    const a: string = 0 as any;
    

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 2021-08-19
      • 2018-05-06
      • 2018-09-29
      • 2021-10-11
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      相关资源
      最近更新 更多