• 如何将变量用作typescript的类型注解


    我们在学习typescript的时候都知道一个概念:变量声明空间

    意思是说,一些用 var 声明的变量,也只能在变量声明空间使用,不能用作类型注解。

    官网中给出的例子是这样的:

    const foo = 123;
    let bar: foo; // ERROR: "cannot find name 'foo'"
    
    • 1
    • 2

    那么在实际使用过程中,如果我们需要将foo作为类型注解我们该怎么办呢?

    其实只需要在变量前面加一个typeof就可以了。

    const foo = 123;
    const bar:typeof foo = 123;
    const bar2:typeof foo = 13; // ERROR: "Type '13' is not assignable to type '123'."
    
    • 1
    • 2
    • 3

    这样就可以直接使用已定义的变量作为类型注解了。

    需要注意的是定义变量用的关键字对结果是有影响的,可以这么理解const
    是严格的,let是宽泛的。

    let foo = 123;
    const bar:typeof foo = 123;
    const bar2:typeof foo = 13; 
    const bar3: typeof foo = '13'; // Type 'string' is not assignable to type 'number'.
    
    • 1
    • 2
    • 3
    • 4

    从上面的例子可以看出,const要求变量必须等于123,而let只需要是个number就可以了。

    我稍微对这个规律做了个总结:

    变量类型constlet
    numberselfnumber
    stringselfstring
    booleanselfself
    nullselfself
    undefinedselfself
    SymbolselfSymbol
    Object遵循Object结构,内部属性类型是宽泛的遵循Object结构,内部属性类型是宽泛的
    Array可以包含数组中已存在的宽泛类型可以包含数组中已存在的宽泛类型

    我们主要来看看ObjectArray的例子吧。

    let foo = {key: 123, a: {b: 1}};
    const bar:typeof foo={key: 12, a:{b:123}}; // success
    const bar1:typeof foo={key: 123}; // Error: Property 'a' is missing in type '{ key: number; }' but required in type '{ key: number; a: { b: number; }; }'.
    
    let foo = [1, '2', 3];
    const bar:typeof foo=[1, 2, '3323', 'true', 1232]; // success
    const bar1:typeof foo=[1, 2, '3323', 'true', false, 1232]; // Error: Type 'boolean' is not assignable to type 'string | number'.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    注:我虽然总结了这些东西,但是完全是出于好奇,我个人是非常不推荐直接使用变量作为类型注解的。还是使用独立的类型注释文件来进行类型定义比较好,既便于维护,也易于理解。除非万不得已,就不要自己折腾自己了。

  • 相关阅读:
    【从头构筑C#知识体系】1.9 特性
    一文让您读懂实时数仓(Apache Doris)
    嵌入式Linux高级案例-移植LVGL到Linux开发板
    汽车电源高压互锁(HVIL)
    FancyBox.js基于JQuery图集弹层插件用法
    玩转数据可视化之R语言ggplot2:(九)网络图绘制
    Oracle EBS R12 DBA(二)
    Vue学习之认识到应用(三)
    C语言指针的详细概念
    Nginx详细配置指南
  • 原文地址:https://blog.csdn.net/sayUonly/article/details/126707653