【问题标题】:How to declare a type as nullable in TypeScript?如何在 TypeScript 中将类型声明为可为空?
【发布时间】:2013-06-17 16:36:29
【问题描述】:

我在 TypeScript 中有一个界面。

interface Employee{
    id: number;
    name: string;
    salary: number;
}

我想将salary 设为可空字段(就像我们可以在 C# 中那样)。这可以在 TypeScript 中实现吗?

【问题讨论】:

    标签: typescript nullable


    【解决方案1】:

    我通过编辑 tsconfig.json 文件解决了这个问题。

    下:"strict": true, 添加这两行:

    "noImplicitAny": false,
    "strictNullChecks": false,
    

    【讨论】:

    • 这不是违背了打字稿的目的吗?肯定有办法将对象属性或对象设置为某种空安全状态吗?
    【解决方案2】:

    要更像 C#,请像这样定义 Nullable 类型:

    type Nullable<T> = T | null;
    
    interface Employee{
       id: number;
       name: string;
       salary: Nullable<number>;
    }
    

    奖励:

    要使 Nullable 表现得像内置的 Typescript 类型,请在根源文件夹的 global.d.ts 定义文件中定义它。这条路径对我有用:/src/global.d.ts

    【讨论】:

    • 我最喜欢的答案 - 直接 无需阅读即可回答问题。
    • 使用它会破坏对象属性的自动完成。例如,如果我们有emp: Partial&lt;Employee&gt;,我们可以做emp.idemp.name 等,但如果我们有emp: Nullable&lt;Employee&gt;,我们不能做emp.id
    • 这是问题的实际答案。
    • @YousufKhan 这是真的。这可能是因为emp 可能为空,id 属性可能无效。为了使代码健壮,您可能应该首先使用if 块来检查空值,如下所示:if (emp) { console.log(emp.id); } 如果您使用这样的if-块,TypeScript 编译器和编辑器“看到”对象块内不为空,因此不会产生错误并允许在 if 块内自动完成。 (它在我的 Visual Studio 2019 编辑器中运行良好,我认为它也可以在 Visual Studio Code 中运行。但我不了解其他编辑器。)
    • @YousufKhan 。 . .当使用emp: Partial&lt;Employee&gt; 时,生成的类型包含来自Employee 的所有属性,但这些属性将为空。 (好吧,undefinedable 在这里可能是更合适的术语。)所以emp 的所有属性都可用,但可以为空。使用emp: Nullable&lt;Employee&gt; 时,emp 变量本身可以为空。如果它不为 null,它应该是一个有效的完整 Employee 实例。您也可以将它们结合起来:emp: Nullable&lt;Partial&lt;Employee&gt;&gt;。在这种情况下,emp 本身可以为空,但当不为空时,它的属性也都可以为空。
    【解决方案3】:

    您可以只实现一个用户定义的类型,如下所示:

    type Nullable<T> = T | undefined | null;
    
    var foo: Nullable<number> = 10; // ok
    var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
    var baz: Nullable<number> = null; // ok
    
    var arr1: Nullable<Array<number>> = [1,2]; // ok
    var obj: Nullable<Object> = {}; // ok
    
     // Type 'number[]' is not assignable to type 'string[]'. 
     // Type 'number' is not assignable to type 'string'
    var arr2: Nullable<Array<string>> = [1,2];
    

    【讨论】:

      【解决方案4】:

      Nullable 类型可以调用运行时错误。 所以我认为最好使用编译器选项--strictNullChecks 并将number | null 声明为类型。同样在嵌套函数的情况下,虽然输入类型为空,但编译器不知道它会破坏什么,所以我建议使用!(感叹号)。

      function broken(name: string | null): string {
        function postfix(epithet: string) {
          return name.charAt(0) + '.  the ' + epithet; // error, 'name' is possibly null
        }
        name = name || "Bob";
        return postfix("great");
      }
      
      function fixed(name: string | null): string {
        function postfix(epithet: string) {
          return name!.charAt(0) + '.  the ' + epithet; // ok
        }
        name = name || "Bob";
        return postfix("great");
      }
      

      参考。 https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

      【讨论】:

      • 两个 cmets:a) 现代 JS 或 TS 可以使用“null-coalesce”运算符??。与“错误”逻辑或运算符|| 相比,这不太可能导致意外错误。 name = name ?? "Bob"; 是用默认值替换 null 的更简洁的方法。 b) 我不会在这段代码中使用!。任何时候你使用!,你都有可能让未来的代码维护者犯错误,从而导致一个罕见的运行时错误:调试起来很痛苦。更安全的是const name2:string = name ?? "Bob";function postfix(...) { return name2.charAt(0) ...
      【解决方案5】:
      type MyProps = {
        workoutType: string | null;
      };
      

      【讨论】:

        【解决方案6】:

        在我看来,联合类型是这种情况下的最佳选择:

        interface Employee{
           id: number;
           name: string;
           salary: number | null;
        }
        
        // Both cases are valid
        let employe1: Employee = { id: 1, name: 'John', salary: 100 };
        let employe2: Employee = { id: 1, name: 'John', salary: null };
        

        编辑:要按预期工作,您应该在tsconfig 中启用strictNullChecks

        【讨论】:

        • 如果你使用 --strictNullChecks (你应该这样做),这是一个有效的解决方案。我不会使用它来支持可选成员,因为它会强制您在所有文字对象上添加显式 null,但对于函数返回值,这是要走的路。
        • 澄清@geon 的建议:接口的optional property? 在属性名称 上声明。 salary?: number 表示salary 可以省略,或者等效地给定值undefined,但不能给它值nullGood demonstration of different declarations using optional and/or null.
        • @ToolmakerSteve 是的。使用salary: number | nullsalary: number | undefined 仍然很棒,因为它会强制您将其设置为某个值,即使该值是undefined。否则很容易忘记。
        【解决方案7】:

        前段时间我也有同样的问题.. ts 中的所有类型都可以为空,因为 void 是所有类型的子类型(例如,与 scala 不同)。

        看看这个流程图是否有帮助 - https://github.com/bcherny/language-types-comparison#typescript

        【讨论】:

        • -1:这根本不是真的。至于void是'所有类型的子类型'(bottom type),请参考this thread。此外,您为 scala 提供的图表也不正确。 Nothing in scala 实际上是最底层的类型。打字稿,atm,没有有底部类型,而scala
        • "所有类型的子类型" != 底部类型。在此处查看 TS 规范 github.com/Microsoft/TypeScript/blob/master/doc/…
        【解决方案8】:

        JavaScript(和 TypeScript)中的所有字段都可以具有值 nullundefined

        您可以使字段可选不同于可为空。

        interface Employee1 {
            name: string;
            salary: number;
        }
        
        var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
        var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
        var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
        var d: Employee1 = { name: null, salary: undefined }; // OK
        
        // OK
        class SomeEmployeeA implements Employee1 {
            public name = 'Bob';
            public salary = 40000;
        }
        
        // Not OK: Must have 'salary'
        class SomeEmployeeB implements Employee1 {
            public name: string;
        }
        

        比较:

        interface Employee2 {
            name: string;
            salary?: number;
        }
        
        var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
        var b: Employee2 = { name: 'Bob' }; // OK
        var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
        var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number
        
        // OK, but doesn't make too much sense
        class SomeEmployeeA implements Employee2 {
            public name = 'Bob';
        }
        

        【讨论】:

        • 看起来strictly nullable types and strict null-checks 已经实现,并将与 Typescript 2.0 一起出现! (或现在typescript@next。)
        • 你确定第一个例子中的 var c 吗?在我看来, var b 和 var c 在那里是一样的。
        • 这是不正确的。 JS 区分 null 和 undefined。正确的代码应该是salary:number|null; 如果你这样做salary?:number; salary = null; 你会得到一个错误。但是,salary = undefined; 在这种情况下可以正常工作。解决方案:使用 Union 即 '|'
        • (投反对票,因为它现在已经过时/不好。)
        • 嗯,为什么不| null。你自己说 undefined 和 null 不一样。 Optional 是未定义的,所以这根本不是答案?
        【解决方案9】:

        只需在可选字段中添加一个问号?

        interface Employee{
           id: number;
           name: string;
           salary?: number;
        }
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-20
        • 2016-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        • 2017-04-30
        • 1970-01-01
        相关资源
        最近更新 更多