【问题标题】:Can an optional parameter be null in TypeScript?TypeScript 中的可选参数可以为空吗?
【发布时间】:2019-12-06 04:22:21
【问题描述】:

根据this article,当在TypeScript 中启用严格的空检查时,您不能将nullundefined 分配给变量,除非它通过联合明确允许。

// required value
let req: string;
req = "Something";  // OK
req = null;      // Error
req = undefined; // Error

// nullable value
let nbl: string | null;
nbl = "Something";  // OK
nbl = null;      // OK
nbl = undefined; // Error

但是 null 在 TypeScript 的 optional 值中是否允许?

// optional value
let opt?: string; // (actually invalid, as optional types cannot be used for variable declarations, but that's not the point, so imagine we are dealing with function parameters or something)
opt = "Something"; // OK
opt = null; // OK? Error?
opt = undefined; // OK

或者是

opt?: string;

相当于

opt: string | undefined;

因此不允许null 就像Microsoft's Coding guidelines 推荐的那样?

【问题讨论】:

    标签: typescript undefined optional nullable


    【解决方案1】:

    编辑:重要提示正如 Quentin C 在下面的评论中指出的那样,这里列出的行为仅在启用严格的 null 检查时出现:"strictNullChecks": true in tsconfig.json


    nullundefined 类型作为单独的类型处理。 optional 类型很特殊,也允许在函数调用中省略参数。

    1.如果没有联合或可选,则只允许类型本身。

    function foo(bar: string) {
        console.info(bar);
    }
    
    foo("Hello World!"); // OK
    foo(null); // Error
    foo(undefined); // Error
    foo() // Error
    

    2。要额外允许null,可以与null 进行联合。

    function foo(bar: string | null) {
        console.info(bar);
    }
    
    foo("Hello World!"); // OK
    foo(null); // OK
    foo(undefined); // Error
    foo() // Error
    

    3.允许undefined 的工作方式类似。请注意,参数不能省略或null

    function foo(bar: string | undefined) {
        console.info(bar);
    }
    
    foo("Hello World!"); // OK
    foo(null); // Error
    foo(undefined); // OK
    foo() // Error
    

    4.您也可以同时允许,但仍必须给出参数。

    function foo(bar: string | null | undefined) {
        console.info(bar);
    }
    
    foo("Hello World!"); // OK
    foo(null); // OK
    foo(undefined); // OK
    foo() // Error
    

    5.使用可选,您可以忽略参数,或传递undefined,但不能传递null

    function foo(bar?: string) {
        console.info(bar);
    }
    
    foo("Hello World!"); // OK
    foo(null); // Error
    foo(undefined); // OK
    foo() // OK
    

    6.为了允许所有三种特殊情况,可选null可以组合使用。

    function foo(bar?: string | null) {
        console.info(bar);
    }
    
    foo("Hello World!"); // OK
    foo(null); // OK
    foo(undefined); // OK
    foo() // OK
    

    此外,可选 仅可用于参数或其他类型声明,例如接口,不能用于常规变量。因为在赋值时省略变量的值是没有意义的。

    因此,

    let d?: string;
    

    没有意义并导致编译错误。

    【讨论】:

    • 对于像我这样没有正确阅读问题的人来说,这里列出的行为仅在启用严格的空检查时才会出现。 “strictNullChecks”:在 tsconfig.json 中为真
    【解决方案2】:

    let d?: string; 将类型声明为string | undefined

    这是因为undefined是JS变量的默认值。

    【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2020-05-06
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多